Tuesday, 5 November 2013

Using ContainerListener on AWT Frame

The following example illustrates using ContainerListener on AWT Frame.

import java.awt.*;
import java.awt.event.*;
class FrameContainerEvent extends Frame implements ContainerListener
{
Button add,remove;
int i;

    public FrameContainerEvent()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("ContainerEvent on AWT Frame");
        setLayout(new FlowLayout());
       
        // Create and add a button
        add=new Button("Add Label");
        add(add);
       
        remove=new Button("Remove Label");
        add(remove);
       
        // Add ActionListener to buttons
        add.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
                addLabel();
            }
        });
       
        remove.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
                removeLabel();
            }
        });
       
        // Add ContainerListener
        addContainerListener(this);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public void addLabel()
    {
        // Add the label
        add(new Label("Label "+i++));
       
        // For updating the UI when the label is added
        javax.swing.SwingUtilities.updateComponentTreeUI(this);       
    }
   
    public void removeLabel()
    {
        // If there are no labels, do nothing
        if(i<1) return;
       
        // Remove the last label
        remove(getComponents()[getComponents().length-1]);
       
        // Decrement i value
        i--;
       
        // Update gui
        javax.swing.SwingUtilities.updateComponentTreeUI(this);
    }
   
    public void componentAdded(ContainerEvent ce)
    {
        Label l=(Label)ce.getChild();
        setTitle("Added "+l.getText());
    }
   
    public void componentRemoved(ContainerEvent ce)
    {
        Label l=(Label)ce.getChild();
        setTitle("Removed "+l.getText());
    }
   
    public static void main(String args[])
    {
        new FrameContainerEvent();
    }
}

ContainerEvent is generated whenever a component is added or removed on/from a container.
getChild(): This method returns the component that is affected (added/removed whatever that applies). This returns Component which is typecasted here to Label
FrameContainerEvent(): Code illustrating the use of ContainerListener on AWT Frame is written here.

Using ContainerListener for AWT Frame

Next: Using ComponentListener for AWT Button
Previous: Using FocusListener on AWT Button

No comments:

Post a Comment