harish
harish

Reputation: 328

How to close a frame in Java without closing the cmd prompt?

Here is the frame (i.e. java.awt.Frame) code. When I click the close button on the window it doesn't close and every time I have to close the the cmd prompt from where I launch this program. How to make it close?

import java.awt.*;

public class FrameExample {

private Frame f;

public FrameExample () {
    f=new Frame("Hi its Harish");
}

public void launchFrame() {
    f.setSize(470,470);
    f.setVisible(true);
}

public static void main(String args[]) {
    FrameExample guiWindow=new FrameExample();
    guiWindow.launchFrame();
}
}

Upvotes: 0

Views: 7947

Answers (6)

l_39217_l
l_39217_l

Reputation: 2110

implement window listener....

inside windowClosed call System.exit(0)

Upvotes: 1

Pratik
Pratik

Reputation: 30855

add this listener into your code

f.addWindowListener(new WindowAdapter(){
   public void windowClosing(WindowEvent we){
      System.exit(0);
   }
});

Upvotes: 2

Chandra Sekar
Chandra Sekar

Reputation: 10853

AWT frame doesn't support setDefaultCloseOperation(). Use,

f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
        f.dispose();
    }
});

Upvotes: 1

SteeveDroz
SteeveDroz

Reputation: 6156

You can change the close operation:

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Upvotes: 0

rascio
rascio

Reputation: 9279

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

It's explained here: http://download.oracle.com/javase/tutorial/uiswing/components/frame.html

Upvotes: 0

ewan.chalmers
ewan.chalmers

Reputation: 16255

If you were using JFrame (swing) rather than Frame (awt), you would use JFrame.setDefaultCloseOperation(int) and specify EXIT_ON_CLOSE.

f.setDefaultCloseOperation(EXIT_ON_CLOSE);

Since you are not, the WindowListener is the way to go.

Upvotes: 0

Related Questions