Monday 31 March 2014

ComponentListener

 


public interface ComponentListener extends EventListener {
    public void componentResized(ComponentEvent e);
    public void componentMoved(ComponentEvent e);
    public void componentShown(ComponentEvent e);
    public void componentHidden(ComponentEvent e);
}

The listener interface for receiving component events. When the component changes its properties like size, location, or visibility changes, the relevant method in the listener object is invoked, and the ComponentEvent is passed to it.

Component events are provided for notification purposes ONLY; The AWT will automatically handle component moves and resizes internally so that GUI layout works properly regardless of whether a program registers a ComponentListener or not.

import java.awt.*;
import java.awt.event.*;

class ComponentListenerInterfEx implements ComponentListener{
 public void componentResized(ComponentEvent e){
  System.out.println("Component resized");
 }
 
 public void componentMoved(ComponentEvent e){
  System.out.println("Component Moved");
 }
 
 public void componentShown(ComponentEvent e){
  System.out.println("Component Shown");
 }
 
 public void componentHidden(ComponentEvent e){
  System.out.println("Component Hidden");
 }
}



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

class ComponentListenerEx{
 public static void main(String args[]){
  JFrame myFrame = new JFrame("Event Handling Example");
  
  /* Create a button */
  JButton myButton = new JButton("Click Me");
  
  myFrame.setVisible(true);
  myFrame.setSize(250, 250);
  
  /* Add Button to the frame */
  myFrame.add(myButton);
  
  ComponentListenerInterfEx obj1 = new ComponentListenerInterfEx();
  myFrame.addComponentListener(obj1);
 }
}


Try to resize, minimize and close the window. You will get below output.




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment