Java Reference
In-Depth Information
To demonstrate, Listing 4-2 associates an
AncestorListener
with the root pane of a
JFrame
.
You'll see the messages
Removed
,
Added
, and
Moved
when the program first starts up. In addition,
you'll see
Moved
messages when you drag the frame around.
Listing 4-2.
Listening for Ancestor Events
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class AncestorSampler {
public static void main (String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("Ancestor Sampler");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
AncestorListener ancestorListener = new AncestorListener() {
public void ancestorAdded(AncestorEvent ancestorEvent) {
System.out.println ("Added");
}
public void ancestorMoved(AncestorEvent ancestorEvent) {
System.out.println ("Moved");
}
public void ancestorRemoved(AncestorEvent ancestorEvent) {
System.out.println ("Removed");
}
};
frame.getRootPane().addAncestorListener(ancestorListener);
frame.setSize(300, 200);
frame.setVisible(true);
frame.getRootPane().setVisible(false);
frame.getRootPane().setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
Listening to Inherited Events of a JComponent
In addition to the ability to listen for an instance of an
AncestorEvent
or
PropertyChangeEvent
with a
JComponent
, the
JComponent
inherits the ability to listen to many other events from its
Container
and
Component
superclasses.