2

When I click on the close(X) button of one frame it closes all the open Frames.

I have used following code for closing the frame

    Frame f2 = new Frame();
        f2.setVisible(true);
        f2.setLayout(null);
        f2.setSize(500,500);
        f2.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent w)
            {
            System.exit(0);
            }       
        });

System.exit(0) make the whole application to close.

How can i close only one Frame??

mnille
  • 1,328
  • 4
  • 16
  • 20
Shankar
  • 2,890
  • 3
  • 25
  • 40
  • 1) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) 2) Why use AWT? See [this answer](http://stackoverflow.com/questions/6255106/java-gui-listeners-without-awt/6255978#6255978) for many good reasons to abandon AWT using components in favor of Swing. – Andrew Thompson Apr 29 '16 at 02:58
  • 3) `f2.setLayout(null);` 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 [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Apr 29 '16 at 02:59

2 Answers2

2

System.exit(); causes the Java VM to terminate completely.

So you need to use JFrame.dispose(); that causes the JFrame window to be destroyed and cleaned up by the operating system.

Frame f2 = new Frame();
    f2.setVisible(true);
    f2.setLayout(null);
    f2.setSize(500,500);
    f2.addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent w)
        {
        f2.dispose();
        }       
    });

Explanation from this post

Community
  • 1
  • 1
Manu AG
  • 188
  • 1
  • 6
1

You can use dispose() too:

import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Work {

    public static void main(String[] args) {
        Frame f2 = new Frame();
        f2.setVisible(true);
        f2.setLayout(null);
        f2.setSize(500, 500);
        f2.
        f2.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent w) {
                w.getWindow().dispose();
            }
        });
    }
}

See more here.

Community
  • 1
  • 1
Tamas Rev
  • 7,008
  • 5
  • 32
  • 49