You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何点击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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 12:52:15