Home » Desktop Java » awt » event » AncestorListener example

About Ilias Tsagklis

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

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 AncestorListener instance.
  • Override the methods that correspond to the events that you want to monitor about the ancestor changes e.g, ancestorAddedancestorMovedancestorRemovedand 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 addAncestorListener to add the AncestorListener to a specific component. Now when you add a this component to another one the event will be handled with the execution of ancestorAdded method.

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");


  AncestorListener ancListener = new AncestorListener() {


public void ancestorAdded(AncestorEvent ancestorEvent) {



public void ancestorMoved(AncestorEvent ancestorEvent) {

    System.out.println("Window Moved");



public void ancestorRemoved(AncestorEvent ancestorEvent) {






  jFrame.setSize(300, 100);


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

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area


Leave a Reply


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

Notify of