关闭打开的框架而不关闭当前

问题描述

我想在打开另一个框架时关闭我的 homeScreen 框架

public class MainClass {

    public static void main(String[] args) {
        JFrame homeScreen = new JFrame("HomeScreen");
        homeScreen.setDefaultCloSEOperation(JFrame.disPOSE_ON_CLOSE);
        EsPanel2 panelloPrimo = new EsPanel2();
        homeScreen.add(panelloPrimo);
        homeScreen.setBounds(0,690,470);
        homeScreen.setLocationRelativeto(null);
        homeScreen.setVisible(true);
    }
}

EsPanel2 是一个扩展 JPanel 的类,并且有一个按钮,点击它后,按钮的 ActionListener 会打开一个全新的框架。

解决方法

有一个按钮,点击它会通过按钮的 ActionListener 打开一个全新的框架

您可以在 ActionListener 中引用带有逻辑的开放框架。类似的东西:

// close existing frame

JButton button = (JButton)event.getSource();
Window window = SwingUtilities.windowForComponent(button);
window.dispose();

// create and show new frame

JFrame frame = new JFrame(...);
...
frame.setVisible( true );