Java WindowEvent getSource()

PreviousNext

Java WindowEvent getSource() The object on which the Event initially occurred.

Syntax

The method getSource() from WindowEvent is declared as:

public Object getSource()

Return

The method getSource() returns the object on which the Event initially occurred

Example

The following code shows how to use Java WindowEvent getSource()

Example 1

import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Main {
    public static void main() {
        Frame frame = new Frame();
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent evt) {
                Frame frame = (Frame) evt.getSource();
                frame.setVisible(false);
                // frame.dispose();
            }
        });
    }
}

Example 2

import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

public class Main {
    public static void main() {
        Frame frame = new Frame();

        WindowListener listener = new WindowAdapter() {
            public void windowOpened(WindowEvent evt) {
                Frame frame = (Frame) evt.getSource();
                System.out.println(frame.getTitle());
            }/*  w  ww  .  d    e  m o 2    s  .  c  o m */

            public void windowClosing(WindowEvent evt) {
                Frame frame = (Frame) evt.getSource();

                System.out.println(frame.getTitle());

            }

            public void windowClosed(WindowEvent evt) {
                Frame frame = (Frame) evt.getSource();
                System.out.println(frame.getTitle());
            }
        };

        frame.addWindowListener(listener);
        frame.setVisible(true);
    }
}

Example 3

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main {
    public static void main(String[] args) {
        JPanel panel = new JPanel();
        panel.add(new JTextField(10));
        panel.add(new JButton("button"));
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);/*  ww   w  .  d   e m o   2   s.   c   o m */
        frame.pack();
        frame.setVisible(true);

        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowIconified(WindowEvent wEvt) {
                ((JFrame) wEvt.getSource()).dispose();
            }

            @Override
            public void windowDeactivated(WindowEvent wEvt) {
                ((JFrame) wEvt.getSource()).dispose();
            }
        });
    }
}
PreviousNext

Related