- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to determine when a Frame or Window is closing in Java
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
Advertisements