event

ContainerListener example

In this example we shall show you how to use a ContainerListener in Java. When you develop an Application with dynamic GUI features it’s very important to monitor the activities of the components that are added or removed from a component container, and that is the job of the ContainerListener.

In short to work with a ContainerListener you have to:

  • Create a new ContainerListener
  • Override the methods that correspond to the events that you want to monitor about the container e.g componentAdded, componentRemoved and customize as you wish the handling of the respective events. Now every time a component in added or removed from the container, the corresponding method will be executed.
  • Use addContainerListener method to add the ContainerListener to the component you want to monitor.

Let’s see the code snippets that follow:

package com.javacodegeeks.snippets.desktop;

import java.awt.Component;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class ContainerListenerExample {

    public static void main(String args[]) {

  JFrame jFrame = new JFrame();

  Container cPane = jFrame.getContentPane();

  ContainerListener containerListener = new ContainerListener() {

ActionListener actiListener = new ActionListener() {

    @Override

    public void actionPerformed(ActionEvent event) {

  System.out.println("Select: " + event.getActionCommand());

    }

};

@Override

public void componentAdded(ContainerEvent event) {

    Component compChild = event.getChild();

    if (compChild instanceof JButton) {

  JButton jButton = (JButton) compChild;

  jButton.addActionListener(actiListener);

    }

}

@Override

public void componentRemoved(ContainerEvent event) {

    Component compChild = event.getChild();

    if (compChild instanceof JButton) {

  JButton Jbutton = (JButton) compChild;

  Jbutton.removeActionListener(actiListener);

    }

}

  };

  cPane.addContainerListener(containerListener);

  cPane.setLayout(new GridLayout(3, 2));

  cPane.add(new JButton("First"));

  cPane.add(new JButton("Second"));

  cPane.add(new JButton("Third"));

  cPane.add(new JButton("Fourth"));

  cPane.add(new JButton("Fifth"));

  jFrame.setSize(400, 300);

  jFrame.show();
    }
}

 
This was an example on how to work with ContainerListener in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button