Monday 31 March 2014

ContainerListener



public interface ContainerListener extends EventListener {
    public void componentAdded(ContainerEvent e);
    public void componentRemoved(ContainerEvent e);
}

The listener interface for receiving container events. Whenever some components added or removed from the container, the events called.
  
void componentAdded(ContainerEvent e)
    Invoked when a component has been added to the container.

void componentRemoved(ContainerEvent e)
    Invoked when a component has been removed from the container.

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

class ContainerListenerInterfEx implements ContainerListener{

 public void componentAdded(ContainerEvent e){
  System.out.println("Component Added");
 }
 
 public void componentRemoved(ContainerEvent e){
  System.out.println("Component Removed");
 }
}


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

class ContainerListenerEx{
 public static void main(String args[])throws Exception{
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  JFrame myFrame = new JFrame("Event Handling Example");
  JPanel buttonPanel;
  ContainerListenerInterfEx obj1 = new ContainerListenerInterfEx();
  int count = 0;
  
  myFrame.setVisible(true);
  myFrame.setSize(250, 250);
  
  String str;
  
  buttonPanel = new JPanel(new GridLayout(1,1));
  buttonPanel.setPreferredSize(new Dimension(200, 75));
  buttonPanel.addContainerListener(obj1);
  myFrame.add(buttonPanel);
  
  /* Create 100 Buttons */
  JButton myButton[] = new JButton[100];
  
  for(int i=0; i < 100; i++){
   myButton[i] = new JButton("Button " +i);
  }
    
  do{
   System.out.println("Enter Y to add one more button OR N to remove Button");
   str = br.readLine();
   /* Add Button to the frame */
   if(str.equals("Y")){
    buttonPanel.add(myButton[count]);
    count++;
   }
   
   /* Remove Button From the Frame */
   if(str.equals("N") && count != 0){ 
     buttonPanel.remove(myButton[--count]);
   }
   
   buttonPanel.revalidate();
   buttonPanel.repaint();
  }while(str.equals("Y") || str.equals("N"));
  System.exit(0);
 }
}

Output Screens






Prevoius                                                 Next                                                 Home

No comments:

Post a Comment