Java Program to determine when a Frame or Window is closing in Java

Java 8Object Oriented ProgrammingProgramming

To determine when a Window is closing in Java, use the WindowListener, which is the listener interface for receiving window events..

WindowListener listener = new WindowAdapter() {
   public void windowClosing(WindowEvent evt) {
      Frame frame = (Frame) evt.getSource();
      System.out.println("Closing = "+frame.getTitle());
   }
};

Above, we have used the windowClosing() method, which is invoked when a window is in the process of being closed −

public void windowClosing(WindowEvent evt) {
   Frame frame = (Frame) evt.getSource();
   System.out.println("Closing = "+frame.getTitle());
}

The following is an example to determine when a Frame or Window is closing in Java −

Example

package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
public class SwingDemo {
   public static void main(String args[]) throws BadLocationException {
      JFrame frame = new JFrame("Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      WindowListener listener = new WindowAdapter() {
         public void windowClosing(WindowEvent evt) {
            Frame frame = (Frame) evt.getSource();
            System.out.println("Closing = "+frame.getTitle());
         }
      };
      Container container = frame.getContentPane();
      JTextPane pane = new JTextPane();
      SimpleAttributeSet attributeSet = new SimpleAttributeSet();
      StyleConstants.setItalic(attributeSet, true);
      StyleConstants.setForeground(attributeSet, Color.black);
      StyleConstants.setBackground(attributeSet, Color.orange);
      pane.setCharacterAttributes(attributeSet, true);
      pane.setText("This is a demo text!");
      JScrollPane scrollPane = new JScrollPane(pane);
      container.add(scrollPane, BorderLayout.CENTER);
      frame.setSize(550, 300);
      frame.addWindowListener(listener); frame.setVisible(true);
   }
}

The output is as follows. The following is visible on Console −

Output


raja
Published on 04-Jun-2019 11:34:38
Advertisements