使用swing调用父窗体的方法

Jam*_*son 1 java swing constructor jbutton actionlistener

我有一个 JFrame 表单StaffListMain,它在按钮单击事件之一中具有以下代码:

private void btnManageLeaveActionPerformed(java.awt.event.ActionEvent evt) {
    // Open the new form and pass the selected staff member
    ManageLeave manageLeaveForm = new ManageLeave(staff.getStaffAt(lstStaff.getSelectedIndex()));
    manageLeaveForm.setVisible(true);
}
Run Code Online (Sandbox Code Playgroud)

StaffListMain类也有一个方法调用writeToFile(),一个我想其他类内使用,如在一个上面的代码段(ManageLeaveForm)。

因此,我需要一种方法来调用另一种形式的方法。这是可能的,还是我必须writeToFile()分成另一个类,然后根据需要在每个单独的类中使用它?

Hov*_*els 5

您可以将当前实例的引用传递给 ManageLeave 实例,方法是为其构造函数提供一个 StaffListMain 字段并将其传递this到该字段中。然后,如果需要,您可以从 ManageLeave 对象中调用调用 StaffListMain 对象的方法。