开发者

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

开发者 https://www.devze.com 2023-03-17 15:46 出处:网络
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 th开发者_如何学Ce cmd prompt from where I launch this pro

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 th开发者_如何学Ce 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();
}
}


add this listener into your code

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


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

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


implement window listener....

inside windowClosed call System.exit(0)


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.


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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


You can change the close operation:

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
0

精彩评论

暂无评论...
验证码 换一张
取 消