Determine when a Frame or Window is Opened in Java

Java 8Object Oriented ProgrammingProgramming

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

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

Above, we have used the windowOpened() method, which is invoked when a window has been opened −

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

The following is an example to determine when a frame or window is opened 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");
      WindowListener listener = new WindowAdapter() {
         public void windowOpened(WindowEvent evt) {
            Frame frame = (Frame) evt.getSource();
            System.out.println("Opened "+frame.getTitle());
         }
      };
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      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("We are learning Java and 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);
   }
}

Output



raja
Updated on 30-Jul-2019 22:30:26

Advertisements