如何点击JInternalFrame中的按钮关闭父级JFrame(A)?
解决方法
你之前的问题出在:新建JFrame(A)对象调用dispose()时,操作的是全新的实例,不是当前正在显示的那个窗口,所以完全没用。要关闭原窗口,必须拿到它的真实引用。
步骤如下:
1. 修改JInternalFrame(Profile)的构造方法,接收JFrame(A)的引用
在Profile类里添加成员变量保存父窗口引用,同时修改构造方法:
import javax.swing.JFrame; public class Profile extends JInternalFrame { private JFrame parentFrame; // 保存JFrame(A)的引用 // 修改构造方法,增加JFrame参数 public Profile(String firstname, String lastname, String gender, String password, JFrame parent) { this.parentFrame = parent; // 原构造方法里的其他代码保持不变 } // 其他原有代码... }
2. 在JFrame(A)中创建Profile时传入自身引用
修改panelProfileMouseClicked方法,创建Profile时把当前JFrame(A)的实例(this)传进去:
private void panelProfileMouseClicked(java.awt.event.MouseEvent evt) { DBConnection connection = new DBConnection(); connection.getData(username); // 传入this,即当前JFrame(A)的实例 Profile profile = new Profile(connection.firstname, connection.lastname, connection.gender, connection.password, this); smallDesktop.removeAll(); smallDesktop.add(profile).setVisible(true); }
3. 在Profile的按钮事件中关闭JFrame(A)
修改btnChangePasswordActionPerformed方法,直接使用保存的父窗口引用调用dispose():
private void btnChangePasswordActionPerformed(java.awt.event.ActionEvent evt) { parentFrame.dispose(); // 关闭原JFrame(A) new ChangePassword().setVisible(true); // 打开JFrame(B) }
这样点击按钮时,就会关闭正在显示的JFrame(A),同时打开JFrame(B)。
内容的提问来源于stack exchange,提问作者Imalka Chandrasena
相关产品推荐
相关产品推荐

