Here you will see how to handle the window closing event of a JFrame
. What you need to do is to implement a java.awt.event.WindowListener
interface and call the frame addWindowListener()
method to add the listener to the frame instance. To handle the closing event implements the windowClosing()
method of the interface.
Instead of implementing the java.awt.event.WindowListener
interface which require us to implement the entire methods defined in the interface, we can create an instance of WindowAdapter
object and override only the method we need, which is the windowsClosing()
method. Let’s see the code snippet below.
package org.kodejava.swing;
import javax.swing.JFrame;
import java.awt.Button;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class WindowClosingDemo extends JFrame {
public static void main(String[] args) {
WindowClosingDemo frame = new WindowClosingDemo();
frame.setSize(new Dimension(500, 500));
frame.add(new Button("Hello World"));
// Add window listener by implementing WindowAdapter class to
// the frame instance. To handle the close event we just need
// to implement the windowClosing() method.
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println("WindowClosingDemo.windowClosing");
System.exit(0);
}
});
// Show the frame
frame.setVisible(true);
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Wonderful program