Page 2 of 2
Here's the code for the componentAdded function:
private void addKeyAndContainerListenerRecursively(Component c)
{
//Add KeyListener to the Component passed as an argument
c.addKeyListener(this);
//Check if the Component is a Container
if(c instanceof Container) {
//Component c is a Container. The following cast is safe.
Container cont = (Container)c;
//Add ContainerListener to the Container.
cont.addContainerListener(this);
//Get the Container's array of children Components.
Component[] children = cont.getComponents();
//For every child repeat the above operation.
for(int i = 0; i < children.length; i++){
addKeyAndContainerListenerRecursively(children[i]);
}
}
}
To accomplish our task, we need to add the EscapeDialog as a KeyListener to the component passed as an argument (this is the newly added component if we're in the first recursion of the function).
Then we check whether or not the component is a container. If it isn't, we're done, because the component doesn't contain
any child components. If the component turns out to be a container, the container requires two additional actions:
EscapeDialog as a ContainerListener to the container, so the EscapeDialog receives notification if other components are added to the container in the futureEscapeDialog as a KeyListenerBecause the EscapeDialog object is a KeyListener of all its descendent components, the function keyPressed will be called whenever a key is pressed and the focus belongs to the Dialog or one of its components:
public void keyPressed(KeyEvent e)
{
int code = e.getKeyCode();
if(code == KeyEvent.VK_ESCAPE){
//Key pressed is the Escape key. Hide this Dialog.
setVisible(false);
}
else if(code == KeyEvent.VK_ENTER){
//Key pressed is the Enter key. Redefine performEnterAction() in subclasses
to respond to pressing the Enter key.
performEnterAction(e);
}
//Insert code to process other keys here
}
If the Escape key is pressed, we hide the dialog by calling function setVisible(false). In addition, you can program a response to any key pressed. For example, on pressing the Enter key, function performEnterAction is called. As it stands now, this function doesn't do anything, but you can redefine it in a subclass to do something useful.
In the constructor of the EscapeDialog we need to add this EscapeDialog to itself as a KeyListener and a ContainerListener:
public EscapeDialog(Frame frame, String title, boolean modal)
{
super(frame, title, modal);
addKeyAndContainerListenerRecursively(this);
}
The source code for this article can be accessed at EscapeDialog.java.txt.
If you derive all your dialog boxes from EscapeDialog, the Escape key will automatically close them. Now you can concentrate on creating specific layouts and functionality for
your dialogs without worrying about the basic functionality that today's users expect.
Listener object on buttons added dynamically to a container, http://igwe4.vub.ac.be/javacursus/Java095.htm