This example show you how to handle JFrame
window events such as windowOpened
, windowClosing
, windowClosed
, etc. For handling these events we need to add a WindowListener
listener to the JFrame
instance. Here we use the WindowAdapter
abstract class and implement the method which event we want to handle.
package org.kodejava.swing;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class WindowListenerDemo extends JFrame {
public WindowListenerDemo() {
initializeComponent();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new WindowListenerDemo().setVisible(true));
}
private void initializeComponent() {
setSize(500, 500);
setTitle("Window Listener");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
// Invoked when a window has been opened.
public void windowOpened(WindowEvent e) {
System.out.println("Window Opened Event");
}
// Invoked when a window is in the process of being closed.
// The close operation can be overridden at this point.
public void windowClosing(WindowEvent e) {
System.out.println("Window Closing Event");
}
// Invoked when a window has been closed.
public void windowClosed(WindowEvent e) {
System.out.println("Window Close Event");
}
// Invoked when a window is iconified.
public void windowIconified(WindowEvent e) {
System.out.println("Window Iconified Event");
}
// Invoked when a window is de-iconified.
public void windowDeiconified(WindowEvent e) {
System.out.println("Window Deiconified Event");
}
// Invoked when a window is activated.
public void windowActivated(WindowEvent e) {
System.out.println("Window Activated Event");
}
// Invoked when a window is de-activated.
public void windowDeactivated(WindowEvent e) {
System.out.println("Window Deactivated Event");
}
// Invoked when a window state is changed.
public void windowStateChanged(WindowEvent e) {
System.out.println("Window State Changed Event");
}
// Invoked when the Window is set to be the focused Window, which means
// that the Window, or one of its sub components, will receive keyboard
// events.
public void windowGainedFocus(WindowEvent e) {
System.out.println("Window Gained Focus Event");
}
// Invoked when the Window is no longer the focused Window, which means
// that keyboard events will no longer be delivered to the Window or any of
// its sub components.
public void windowLostFocus(WindowEvent e) {
System.out.println("Window Lost Focus Event");
}
});
}
}
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