Skip to Content

Create Frame Window With Window Close Event Example

  1. /*
  2.         Create Frame Window With Window Close Event Example
  3.         This java example shows how to create frame window and handle windowClosing
  4.         event using WindowAdapter class.
  5. */
  6.  
  7. import java.awt.Frame;
  8. import java.awt.event.WindowAdapter;
  9. import java.awt.event.WindowEvent;
  10.  
  11. /*
  12. * To create a stand alone window, class should be extended from
  13. * Frame and not from Applet class.
  14. */
  15.  
  16. public class CreateWindowWithEventsExample extends Frame{
  17.  
  18.         CreateWindowWithEventsExample(String title){
  19.                 //call the superclass constructor with the specified title
  20.                 super(title);  
  21.                
  22.                 //add window event adapter
  23.                 addWindowListener(new MyWindowAdapter(this));
  24.                
  25.                 //set window size using setSize method
  26.                 this.setSize(300,300);
  27.                
  28.                 //show window using setVisible method
  29.                 this.setVisible(true);
  30.         }
  31.        
  32.         //extend WindowAdapter
  33.         class MyWindowAdapter extends WindowAdapter{
  34.                
  35.                 CreateWindowWithEventsExample myWindow = null;
  36.                
  37.                 MyWindowAdapter(CreateWindowWithEventsExample myWindow){
  38.                         this.myWindow = myWindow;
  39.                 }
  40.                
  41.                 //implement windowClosing method
  42.                 public void windowClosing(WindowEvent e) {
  43.                         //hide the window when window's close button is clicked
  44.                         myWindow.setVisible(false);                    
  45.                 }
  46.         }
  47.        
  48.         public static void main(String[] args) {
  49.                 CreateWindowWithEventsExample myWindow =
  50.                                         new CreateWindowWithEventsExample("Window with event Example");
  51.         }
  52. }

Example Output