closing an opened frame without closing the current

30 Views Asked by At

I want to close my homeScreen Frame upon opening another Frame

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, 0, 690, 470);
        homeScreen.setLocationRelativeTo(null);
        homeScreen.setVisible(true);
    }
}

The EsPanel2 is a class that extends JPanel and has a button that, upon clicking it, opens up an entirely new Frame by the ActionListener of the button.

1

There are 1 best solutions below

0
camickr On

has a button upon clicking it it opens up an entirely new Frame by the ActionListener of the button

You can reference the open frame with logic in your ActionListener. Something like:

// 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 );