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

  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.

(No Ratings Yet)
Start the discussion Views Tweet it!

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

avatar
  Subscribe  
Notify of