Sunday 6 April 2014

WindowFocusListener


The listener interface for receiving WindowEvents. When the Window's status changes by virtue of it being opened, closed, activated, deactivated, iconified, or deiconified, or by focus being transferred into or out of the Window, the relevant method in the listener object is invoked, and the WindowEvent is passed to it.


public interface WindowFocusListener extends EventListener {
    public void windowGainedFocus(WindowEvent e);
    public void windowLostFocus(WindowEvent e);
}

void windowGainedFocus(WindowEvent e)
Invoked when the Window is set to be the focused Window, which means that the Window, or one of its subcomponents, will receive keyboard events.

void windowLostFocus(WindowEvent e)
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


import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class WindowFocusListenerEx{
 JTextArea displayArea;
 TextField typingArea;
 JFrame frame1;
  
 WindowFocusListenerEx(){
  
  /* Initialize typingArea */
  typingArea = new TextField(20);
  
  /* Initialize Display Area */
  displayArea = new JTextArea();
  displayArea.setEditable(false);
  JScrollPane scrollPane = new JScrollPane(displayArea);
  scrollPane.setPreferredSize(new Dimension(150, 200));
   
  /* Initialize Frame */
  frame1 =new JFrame("Sample Frame");
  frame1.pack();
  frame1.setVisible(true);
  frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame1.getContentPane().add(typingArea, BorderLayout.PAGE_START);
  frame1.getContentPane().add(scrollPane, BorderLayout.CENTER);
  frame1.setSize(300, 500);
    
  frame1.addWindowFocusListener(new WindowFocusListener(){
   public void windowGainedFocus(WindowEvent e){
    displayArea.append("Window Focussed\n");
   } 
   public void windowLostFocus(WindowEvent e){
    displayArea.append("Window Lost Focus\n");
   } 
  });   
 }
 
 public static void main(String args[]){
  new WindowFocusListenerEx();
 }
}

Click the frame and unfocus the frame. You can see the below results.







Prevoius                                                 Next                                                 Home

No comments:

Post a Comment