-1

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.

Abra
  • 19,142
  • 7
  • 29
  • 41
  • Pass a reference to `homeScreen` to the `EsPanel2`. Then call `homeScreen.setVisible(false)` after opening the 2nd frame. – Reto Höhener Jan 10 '21 at 15:19
  • @RetoHöhener how may I pass a reference from the mainClass to the EsPanel2 class ? Should I make any casting ? sorry for being such a noob – Mohamed Mada Jan 10 '21 at 16:15
  • For such fundamental questions, it's probably best to read a Java tutorial or ask a peer (or check my profile). – Reto Höhener Jan 10 '21 at 16:24
  • 1) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) 2) Use a [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) as shown in [this answer](http://stackoverflow.com/a/5786005/418556). 3) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for .. – Andrew Thompson Jan 10 '21 at 18:40
  • ,, [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Jan 10 '21 at 18:40

1 Answers1

0

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 );
Abra
  • 19,142
  • 7
  • 29
  • 41
camickr
  • 321,443
  • 19
  • 166
  • 288