I’m coding GUI for my Java project. Here are some info:
- I have an interface EmployeeController.
public interface EmployeeController {
void addEmployee(Employee employee);
Employee getEmployeeById(int employeeId);
void updateEmployee(Employee employee);
void deleteEmployee(int employeeId);
List<Employee> getAllEmployees();
}
- I have EmployeeControllerImpl implements EmployeeController, the methods are coded here.
- Then I code my JFrame AddEmploye where I want to add employee details into text fields and a button to save them.
public class AddEmployee extends javax.swing.JFrame {
private EmployeeController employeeController;
// Constructor to accept Controller
public AddEmployee(EmployeeController employeeController) {
this.employeeController = employeeController;
initComponents();
addActionListeners();
}
// Method to add action listeners to components
private void addActionListeners() {
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Save button clicked");
saveButtonActionPerformed(evt);
}
});
}
// Button method
private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {
Employee employee = new Employee();
employee.setName(nameText.getText());
employee.setAddress(addressText.getText());
employee.setPhoneNumber(phoneNumberText.getText());
try {
employee.setAge(Integer.parseInt(ageText.getText()));
employee.setSalary(Double.parseDouble(salaryText.getText()));
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "Invalid input format.");
return;
}
employee.setGender(genderText.getText());
employee.setPosition(positionText.getText());
employeeController.addEmployee(employee);
JOptionPane.showMessageDialog(this, "Employee added successfully!");
}
// Rest of the pre-generated code by Swing
}
So when I run the frame and click on Save button. The program seemingly stopped at constructor with:
Cannot invoke “EmployeeController.addEmployee(Employee)” because “this.employeeController” is null.
I have been looking into this problem for a while but still clueless.
New contributor
Nguyên Trần is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.