event
AncestorListener example with timer
In this example we are going to see how AncestorListener can be paired with a timer in Java. This is very useful when you add or remove components to your Java Application and you want to monitor the relationship changes that follow these actions.
Basically, all you have to do in order to work with AncestorListener with a timer in Java is:
- Create a new
AncestorListenerinstance. - Override the methods that correspond to the events that you want to monitor about the ancestor changes e.g,
ancestorAdded,ancestorMoved,ancestorRemovedand customize as you wish the handling of the respective events. Now every time one of these events occurs, the corresponding method will be executed. - Use
addAncestorListenerto add theAncestorListenerto a specific component. Now when you add a this component to another one the event will be handled with the execution ofancestorAddedmethod. - Use a
TimerTaskand aTimerto schedule the display of the components.
Let’s take a look a the code snippet that follows:
package com.javacodegeeks.snippets.desktop;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
public class Ancestor {
public static void main(String args[]) {
final JFrame jFrame = new JFrame();
Container cPane = jFrame.getContentPane();
JButton jButton = new JButton("Hide for 5 seconds!");
ActionListener actListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
jFrame.setVisible(false);
TimerTask schedule = new TimerTask() {
@Override
public void run() {
jFrame.setVisible(true);
}
};
Timer timer = new Timer();
timer.schedule(schedule, 5000);
}
};
jButton.addActionListener(actListener);
AncestorListener ancestorListener = new AncestorListener() {
@Override
public void ancestorAdded(AncestorEvent event) {
System.out.println("Added");
dumpInfo(event);
}
@Override
public void ancestorMoved(AncestorEvent event) {
System.out.println("Moved");
dumpInfo(event);
}
@Override
public void ancestorRemoved(AncestorEvent event ){
System.out.println("Removed");
dumpInfo(event);
}
private void dumpInfo(AncestorEvent event) {
System.out.println(" Ancestor: " + name(event.getAncestor()));
System.out.println(" AncestorParent: "
+ name(event.getAncestorParent()));
System.out.println(" Component: " + name(event.getComponent()));
}
private String name(Container container) {
return (container == null) ? null : container.getName();
}
};
jButton.addAncestorListener(ancestorListener);
cPane.add(jButton, BorderLayout.NORTH);
jFrame.setSize(500, 400);
jFrame.setVisible(true);
}
}
This was an example on how to work with AncestorListner in Java.

