event
AncestorListener example
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 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.
Let’s take a look a the code snippet that follows:
package com.javacodegeeks.snippets.desktop;
import javax.swing.JFrame;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
public class Anc {
public static void main(String args[]) {
JFrame jFrame = new JFrame("Move this Window");
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
AncestorListener ancListener = new AncestorListener() {
@Override
public void ancestorAdded(AncestorEvent ancestorEvent) {
}
@Override
public void ancestorMoved(AncestorEvent ancestorEvent) {
System.out.println("Window Moved");
}
@Override
public void ancestorRemoved(AncestorEvent ancestorEvent) {
}
};
jFrame.getRootPane().addAncestorListener(ancListener);
jFrame.getRootPane().setVisible(false);
jFrame.getRootPane().setVisible(true);
jFrame.setSize(300, 100);
jFrame.setVisible(true);
}
}
This was an example on how to work with AncestorListener in Java.


Great contents