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 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.

Ilias Tsagklis

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

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

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
AlixaProDev
3 years ago

Great contents

Back to top button