Передача объекта из одного класса в другой класс

#object #parameters

Вопрос:

В настоящее время я работаю над программой Java, которая работает в MySQL. Целью этой программы является выполнение операций CRUD. Моя кнопка «Создать» работает, и графический интерфейс считывает данные из базы данных и отображает информацию в виде таблицы. У меня возникли проблемы с запуском кнопки обновления и удаления. Проблема в том, что я использую «getSelectionModel().getSelectedItem()» для получения информации о выделенных строках, но у меня возникли проблемы с передачей ее в другой класс для выполнения кода SQL. Каждый раз, когда я запускаю эту программу, информация из таблицы не передается в новый класс. У меня есть класс модели под названием Employee, класс контроллера для начального графического интерфейса и класс контроллера для графического интерфейса обновления.

Класс сотрудников

 package application;  import java.math.BigDecimal; import java.math.BigInteger; import java.sql.*;  public class Employee {  private UpdateExistingEntry updateExistingEntry;  private int employee_id; private String first_name; private String last_name; private Date start_date; private int start_salary; private int contract_signed; private int ssn; private Date birthday; private BigInteger phone_number; private String emergency_contact_name; private BigInteger emergency_contact_number;    public Employee(int employee_id, String first_name, String last_name, Date start_date, int start_salary,  int contract_signed, int ssn, Date birthday, BigInteger phone_number, String emergency_contact_name,  BigInteger emergency_contact_number) {  super();  this.employee_id = employee_id;  this.first_name = first_name;  this.last_name = last_name;  this.start_date = start_date;  this.start_salary = start_salary;  this.contract_signed = contract_signed;  this.ssn = ssn;  this.birthday = birthday;  this.phone_number = phone_number;  this.emergency_contact_name = emergency_contact_name;  this.emergency_contact_number = emergency_contact_number; }    public int getEmployee_id() {  return employee_id; }  public void setEmployee_id(int employee_id) {  this.employee_id = employee_id; }  public String getFirst_name() {  return first_name; }  public void setFirst_name(String first_name) {  this.first_name = first_name; }  public String getLast_name() {  return last_name; }  public void setLast_name(String last_name) {  this.last_name = last_name; }  public Date getStart_date() {  return start_date; }  public void setStart_date(Date start_date) {  this.start_date = start_date; }  public int getStart_salary() {  return start_salary; }  public void setStart_salary(int start_salary) {  this.start_salary = start_salary; }  public int getContract_signed() {  return contract_signed; }  public void setContract_signed(int contract_signed) {  this.contract_signed = contract_signed; }  public int getSsn() {  return ssn; }  public void setSsn(int ssn) {  this.ssn = ssn; }  public Date getBirthday() {  return birthday; }  public void setBirthday(Date birthday) {  this.birthday = birthday; }  public BigInteger getPhone_number() {  return phone_number; }  public void setPhone_number(BigInteger phone_number) {  this.phone_number = phone_number; }  public String getEmergency_contact_name() {  return emergency_contact_name; }  public void setEmergency_contact_name(String emergency_contact_name) {  this.emergency_contact_name = emergency_contact_name; }  public BigInteger getEmergency_contact_number() {  return emergency_contact_number; }  public void setEmergency_contact_number(BigInteger emergency_contact_number) {  this.emergency_contact_number = emergency_contact_number; }  }  

Первый класс контроллера для tableview

 package application;  import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button;  import java.io.IOException; import java.math.BigInteger; import java.net.URL; import java.sql.*;  import java.util.ResourceBundle;    import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent;  import javafx.scene.control.Label;  import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.stage.Stage; import javafx.scene.control.TableColumn;  public class FinalProjectController implements Initializable { @FXML private TableViewlt;Employeegt; tableEmployee; @FXML private TableColumnlt;Employee, Integergt; columnEmployeeID; @FXML private TableColumnlt;Employee, Stringgt; columnFirstName; @FXML private TableColumnlt;Employee, Stringgt; columnLastName; @FXML private TableColumnlt;Employee, Dategt; columnStartDate; @FXML private TableColumnlt;Employee, Integergt; columnStartingSalary; @FXML private TableColumnlt;Employee, Integergt; columnContractSigned; @FXML private TableColumnlt;Employee, Integergt; columnSSN; @FXML private TableColumnlt;Employee, Dategt; columnBirthday; @FXML private TableColumnlt;Employee, BigIntegergt; columnPNumber; @FXML private TableColumnlt;Employee, Stringgt; columnEmergencyName; @FXML private TableColumnlt;Employee, BigIntegergt; columnEmergencyNumber; @FXML private Button btnCreateEmployee; @FXML private Button btnSearchEmployee; @FXML private Button btnUpdateEmployee; @FXML private Button btnDeleteEmployee; @FXML private Button btnRefresh; @FXML private Label labelTable;  private Employee employee;  private int employeeID = 0; private String firstName = ""; private String lastName = ""; private String fullName = ""; private Date startDate; private int startSalary; private int contract; private int ssn; private Date birthday; private BigInteger phoneNumber; private String emergencyContactName; private BigInteger emergencyContactNumber;   ObservableListlt;Employeegt; empList = FXCollections.observableArrayList();  @Override public void initialize(URL arg0, ResourceBundle arg1) {    try {  Connection myConn = DBConnection.connect();  ResultSet myRs = myConn.createStatement().executeQuery("select * from project_employee");    System.out.println(myRs.toString());    while (myRs.next()) {  empList.add(new Employee(myRs.getInt("employee_id"), myRs.getString("first_name"), myRs.getString("last_name"),   myRs.getDate("start_date"), myRs.getInt("start_salary"), myRs.getInt("contract_signed"),   myRs.getInt("ssn"), myRs.getDate("birthday"), myRs.getObject("phone_number", BigInteger.class),   myRs.getString("emergency_contact_name"), myRs.getObject("emergency_contact_number", BigInteger.class)));    }    } catch (SQLException exc) {  exc.printStackTrace();  }    columnEmployeeID.setCellValueFactory(new PropertyValueFactorylt;gt;("employee_id"));  columnFirstName.setCellValueFactory(new PropertyValueFactorylt;gt;("first_name"));  columnLastName.setCellValueFactory(new PropertyValueFactorylt;gt;("last_name"));  columnStartDate.setCellValueFactory(new PropertyValueFactorylt;gt;("start_date"));  columnStartingSalary.setCellValueFactory(new PropertyValueFactorylt;gt;("start_salary"));  columnContractSigned.setCellValueFactory(new PropertyValueFactorylt;gt;("contract_signed"));  columnSSN.setCellValueFactory(new PropertyValueFactorylt;gt;("ssn"));  columnBirthday.setCellValueFactory(new PropertyValueFactorylt;gt;("birthday"));  columnPNumber.setCellValueFactory(new PropertyValueFactorylt;gt;("phone_number"));  columnEmergencyName.setCellValueFactory(new PropertyValueFactorylt;gt;("emergency_contact_name"));  columnEmergencyNumber.setCellValueFactory(new PropertyValueFactorylt;gt;("emergency_contact_number"));      tableEmployee.setItems(empList);   }    // Event Listener on Button[#btnCreateEmployee].onAction @FXML public void createNewEmployee(ActionEvent event) {  try {  CreateBox.show("Create Employee", "Insert Information");  }  catch (Exception exc) {  exc.printStackTrace();  }  }  // Event Listener on Button[#btnSearchEmployee].onAction @FXML public void searchEmployee(ActionEvent event) {     } // Event Listener on Button[#btnUpdateEmployee].onAction @FXML public void updateEmployee(ActionEvent event) {  try {    //creating object for the updatewindow  UpdateGUI show = new UpdateGUI();    //opening update window  show.showUpdateExistingEntry();    employee = tableEmployee.getSelectionModel().getSelectedItem();  employeeID = employee.getEmployee_id();  firstName = employee.getFirst_name();  lastName = employee.getLast_name();  fullName = firstName   " "   lastName;  startDate = employee.getStart_date();  startSalary = employee.getStart_salary();  contract = employee.getContract_signed();  ssn = employee.getSsn();  birthday = employee.getBirthday();  phoneNumber = employee.getPhone_number();  emergencyContactName = employee.getEmergency_contact_name();  emergencyContactNumber = employee.getEmergency_contact_number();  UpdateExistingEntry updateExistingEntry = new UpdateExistingEntry();  updateExistingEntry.selectedEmployeeRow(employee);  updateExistingEntry.setOldRowInformation(employeeID, firstName, lastName, fullName, startDate, startSalary, contract, ssn, birthday, phoneNumber, emergencyContactName, emergencyContactNumber);    //Create error catching for when field is not selected    //creating employee object to get information from the selected rows    } catch (Exception e) {  e.printStackTrace();  }  } // Event Listener on Button[#btnDeleteEmployee].onAction @FXML public void deleteEmployee(ActionEvent event) throws Exception {    DeleteWindow delete = new DeleteWindow();  delete.start();     } // Event Listener on Button[#btnRefresh].onAction @FXML public void refreshDataFromDatabase(ActionEvent event) {  empList.clear();  initialize(null, null); }      }  

The second Controller Class for the update window

 package application;  import java.math.BigInteger; import java.net.URL; import java.math.BigDecimal; import java.sql.*; import java.util.ArrayList; import java.util.ResourceBundle; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.geometry.Pos; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.scene.layout.StackPane; import javafx.scene.control.*; import javafx.scene.layout.VBox;  public class UpdateExistingEntry implements Initializable {  @FXML private Button btnUpdate;  @FXML private Button btnToCancel;  @FXML private Label labelEmployeeID;  @FXML private Label labelFirstName;  @FXML private Label labelLastName;  @FXML private Label labelSSN;  @FXML private Label labelBirthDate;  @FXML private Label labelPhoneNumber;  @FXML private Label labelSalary;  @FXML private Label labelStartDate;  @FXML private Label labelContract;  @FXML private Label labelEmergencyName;  @FXML private Label labelEmergencyNumber;  @FXML private TextField textFieldEmployeeID;   @FXML private TextField textFieldFirstName;   @FXML private TextField textFieldLastName;  @FXML private TextField textFieldSSN;   @FXML private TextField textFieldBirthDate;   @FXML private TextField textFieldPhoneNumber;   @FXML private TextField textFieldSalary;  @FXML private TextField textFieldEmergencyName;  @FXML private TextField textFieldStartDate;  @FXML private TextField textFieldEmergencyNumber;  @FXML private ChoiceBox menuContract;  @FXML private Label labelUserName;  private Employee employee;  private FinalProjectController finalProjectController;  private int employeeID; private String fullUserName; private String firstName; private String lastName; private Date startDate; private int startSalary; private int contract; private int ssn; private Date birthDay; private BigInteger phoneNumber; private String emergencyContactName; private BigInteger emergencyContactNumberr;  //method to set the employee object with employee object from FinalProjectController public void selectedEmployeeRow(Employee employee) {  this.employee = employee;  } //method used in FinalProjectController to fill the variables with information from selected row from FinalProjectcontroller public void setOldRowInformation(int employeeID, String firstName, String lastName, String fullName, Date startDate, int startSalary, int contract, int ssn, Date birthDay, BigInteger phoneNumber,  String emergencyContactName, BigInteger emergencyContactNumber) {    this.employeeID = employeeID;  this.firstName = firstName;  this.lastName = lastName;  this.fullUserName = firstName   " "   lastName;  this.startDate = startDate;  this.startSalary = startSalary;  this.contract = contract;  this.ssn = ssn;  this.birthDay = birthDay;  this.phoneNumber = phoneNumber;  this.emergencyContactName = emergencyContactName;  this.emergencyContactNumberr = emergencyContactNumber;   }    //The following methods check if the textfield has input and sets the input to the either the original value or to the new textfield vlue private String changeFirstName(String firstName) {  if(textFieldFirstName != null) {  firstName = textFieldFirstName.getText();  return firstName;  }else {  return firstName;  }   }  private String changeLastName(String lastName) {  if(textFieldLastName != null) {  lastName = textFieldLastName.getText();  return lastName;  }else {  return lastName;  } }  private String changeEmergencyContactName(String contactName) {  if(textFieldEmergencyName != null) {  contactName = textFieldEmergencyName.getText();  return contactName;  }else {  return contactName;  } }  private int changeEmployeeID(int employeeID) {  if(textFieldEmployeeID != null) {  employeeID = Integer.parseInt(textFieldEmployeeID.getText());  return employeeID;  }else {  return employeeID;  } }  private int changeSSN(int ssn) {  if(textFieldSSN != null) {  ssn = Integer.parseInt(textFieldSSN.getText());  return ssn;  }else {  return ssn;  } }  /**  * private Date changeBirthDate(Date birthDate) {  * if(textFieldBirthDate != null) {  * birthDate = textFieldBirthDate.getText();  * return birthDate;  * }else{  * return birthDate;  * }  * }  */  /**  * private BigInteger changePhoneNumber(BigInteger phoneNumber) {  * if(textFieldPhoneNumber != null) {  * phoneNumber = textFieldBirthDate.getText();  * return phoneNumber;  * }else{  * return phoneNumber;  * }  * }  */  /**  * private Date changeStartDate(Date startDate) {  * if(textFieldStartDate != null) {  * startDate = textFieldStartDate.getText();  * return startDate;  * }else {  * return startDate  * }  * }  */  private int changeSalary(int salary) {  if(textFieldSalary != null) {  salary = Integer.parseInt(textFieldSalary.getText());  return salary;  }else {  return salary;  } }  /**  * private BigInteger changeEmergencyPhoneNumber(BigInteger emergencyPhoneNumber) {  * if(textFieldEmergencyNumber != null) {  * emergencyPhoneNumber = textFieldEmergencyNumber.getText();  * return emergencyPhoneNumber;  * }else {  * return emergencyPhoneNumber;  * }  * }  */  private int changeContract(ChoiceBoxlt;Stringgt; list) {  if(list.getValue() == "yes" ) {  int i = 1;  return i;  }else {  int i = 0;  return i;  } }    //Method to update the information in sql public void makeSQLChanges() throws SQLException {    System.out.println("Start of SQL updaate");    String oldFirstName = firstName;  String oldLastName = lastName;  int oldEmployeeID = employeeID;    //calling the change methods to change the required fields to match what has been inputed in the textfields  firstName = changeFirstName(firstName);  lastName = changeLastName(lastName);  emergencyContactName = changeEmergencyContactName(emergencyContactName);  employeeID = changeEmployeeID(employeeID);  ssn = changeSSN(ssn);  //Date brithDate = changeBirthDate(employee.getBirthday());  //BigInteger phoneNumber = changePhoneNumber(employee.getPhone_number());  //Date startDate = changeStartDate(employee.getStart_date());  startSalary = changeSalary(startSalary);  //BigInteger emergencyPhoneNumber = changeEmergencyPhoneNumber(employee.getEmergency_contact_number());  //int contract = changeContract(menuContract);  System.out.println(employee.getFirst_name());  System.out.println(oldFirstName   " "   oldEmployeeID   " "   oldLastName   " "   lastName   " "   ssn);    Connection myConn = DBConnection.connect();  PreparedStatement myStmt = null;  //Remeber to add birthdate, startdate,contract signed, phonenumber, emergencyphonenumber  String SQL_Update = "update project_employee "    "set employee_id=?, first_name=?, last_name=?, start_salary=?, ssn=?, emergency_contact_name=? "    "where employee_id=? and first_name=? and last_name=?";  myStmt = myConn.prepareStatement(SQL_Update);    try {  //These first setters use the info from the textfields. They match the set in the SQL_Update String  myStmt.setInt(1, employeeID);  myStmt.setString(2, firstName);  myStmt.setString(3, lastName);  myStmt.setInt(4, startSalary);  myStmt.setInt(5, ssn);  myStmt.setString(6, emergencyContactName);    //These setters match the where in the SQL_Update String  myStmt.setInt(7, oldEmployeeID);  myStmt.setString(8, oldFirstName);  myStmt.setString(9, oldLastName);    myStmt.executeUpdate();   System.out.println(oldFirstName   " "   lastName   " "   ssn);  }catch(Exception e) {  e.printStackTrace();  }finally {    if(myConn != null)   {  myConn.close();    }if(myStmt != null) {  myStmt.close();  }  } } //update button @FXML public void updateTheSelectedRow(ActionEvent event) throws SQLException {      //refrencing the finalDecisionToUpdate class to ask the user if they really want to update the info  boolean ans = FinalDecisionToUpdate.show();    //if they click update on the finalDecisionToUpdate window, the class returns a boolean of true  if(ans) {  makeSQLChanges();  cancelUpdate(null);  }   } //cancel update button @FXML public void cancelUpdate(ActionEvent event) {    Stage stage = (Stage) btnToCancel.getScene().getWindow();  stage.close();   } @Override public void initialize(URL arg0, ResourceBundle arg1) {      //labelUserName.setText(finalProjectController.getSelectedFullName());  menuContract.getItems().add("yes");  menuContract.getItems().add("no");   }    }  

If any more info is needed I can add more.