|
Object
;
* the <code>String indicates the type of object and
* is one of the following:
* <code>containerListenerK indicating an
* <code>ContainerListener object;
* the <code>Container's FocusTraversalPolicy
,
* or <code>null
*
* @see AWTEventMulticaster#save(java.io.ObjectOutputStream, java.lang.String, java.util.EventListener)
* @see Container#containerListenerK
* @see #readObject(ObjectInputStream)
*/
private void writeObject(ObjectOutputStream s) throws IOException {
ObjectOutputStream.PutField f = s.putFields();
f.put("ncomponents", component.size());
f.put("component", getComponentsSync());
f.put("layoutMgr", layoutMgr);
f.put("dispatcher", dispatcher);
f.put("maxSize", maxSize);
f.put("focusCycleRoot", focusCycleRoot);
f.put("containerSerializedDataVersion", containerSerializedDataVersion);
f.put("focusTraversalPolicyProvider", focusTraversalPolicyProvider);
s.writeFields();
AWTEventMulticaster.save(s, containerListenerK, containerListener);
s.writeObject(null);
if (focusTraversalPolicy instanceof java.io.Serializable) {
s.writeObject(focusTraversalPolicy);
} else {
s.writeObject(null);
}
}
/**
* Deserializes this <code>Container from the specified
* <code>ObjectInputStream.
* <ul>
* <li>Reads default serializable fields from the stream.
* <li>Reads a list of serializable ContainerListener(s) as optional
* data. If the list is null, no Listeners are installed.</li>
* <li>Reads this Container's FocusTraversalPolicy, which may be null,
* as optional data.</li>
* </ul>
*
* @param s the <code>ObjectInputStream to read
* @serial
* @see #addContainerListener
* @see #writeObject(ObjectOutputStream)
*/
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException
{
ObjectInputStream.GetField f = s.readFields();
Component [] tmpComponent = (Component[])f.get("component", EMPTY_ARRAY);
int ncomponents = (Integer) f.get("ncomponents", 0);
component = new java.util.ArrayList<Component>(ncomponents);
for (int i = 0; i < ncomponents; ++i) {
component.add(tmpComponent[i]);
}
layoutMgr = (LayoutManager)f.get("layoutMgr", null);
dispatcher = (LightweightDispatcher)f.get("dispatcher", null);
// Old stream. Doesn't contain maxSize among Component's fields.
if (maxSize == null) {
maxSize = (Dimension)f.get("maxSize", null);
}
focusCycleRoot = f.get("focusCycleRoot", false);
containerSerializedDataVersion = f.get("containerSerializedDataVersion", 1);
focusTraversalPolicyProvider = f.get("focusTraversalPolicyProvider", false);
java.util.List<Component> component = this.component;
for(Component comp : component) {
comp.parent = this;
adjustListeningChildren(AWTEvent.HIERARCHY_EVENT_MASK,
comp.numListening(AWTEvent.HIERARCHY_EVENT_MASK));
adjustListeningChildren(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK,
comp.numListening(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
adjustDescendants(comp.countHierarchyMembers());
}
Object keyOrNull;
while(null != (keyOrNull = s.readObject())) {
String key = ((String)keyOrNull).intern();
if (containerListenerK == key) {
addContainerListener((ContainerListener)(s.readObject()));
} else {
// skip value for unrecognized key
s.readObject();
}
}
try {
Object policy = s.readObject();
if (policy instanceof FocusTraversalPolicy) {
focusTraversalPolicy = (FocusTraversalPolicy)policy;
}
} catch (java.io.OptionalDataException e) {
// JDK 1.1/1.2/1.3 instances will not have this optional data.
// e.eof will be true to indicate that there is no more data
// available for this object. If e.eof is not true, throw the
// exception as it might have been caused by reasons unrelated to
// focusTraversalPolicy.
if (!e.eof) {
throw e;
}
}
}
/*
* --- Accessibility Support ---
*/
/**
* Inner class of Container used to provide default support for
* accessibility. This class is not meant to be used directly by
* application developers, but is instead meant only to be
* subclassed by container developers.
* <p>
* The class used to obtain the accessible role for this object,
* as well as implementing many of the methods in the
* AccessibleContainer interface.
* @since 1.3
*/
protected class AccessibleAWTContainer extends AccessibleAWTComponent {
/**
* JDK1.3 serialVersionUID
*/
private static final long serialVersionUID = 5081320404842566097L;
/**
* Returns the number of accessible children in the object. If all
* of the children of this object implement <code>Accessible,
* then this method should return the number of children of this object.
*
* @return the number of accessible children in the object
*/
public int getAccessibleChildrenCount() {
return Container.this.getAccessibleChildrenCount();
}
/**
* Returns the nth <code>Accessible child of the object.
*
* @param i zero-based index of child
* @return the nth <code>Accessible child of the object
*/
public Accessible getAccessibleChild(int i) {
return Container.this.getAccessibleChild(i);
}
/**
* Returns the <code>Accessible child, if one exists,
* contained at the local coordinate <code>Point.
*
* @param p the point defining the top-left corner of the
* <code>Accessible, given in the coordinate space
* of the object's parent
* @return the <code>Accessible, if it exists,
* at the specified location; else <code>null
*/
public Accessible getAccessibleAt(Point p) {
return Container.this.getAccessibleAt(p);
}
/**
* Number of PropertyChangeListener objects registered. It's used
* to add/remove ContainerListener to track target Container's state.
*/
private volatile transient int propertyListenersCount = 0;
protected ContainerListener accessibleContainerHandler = null;
/**
* Fire <code>PropertyChange listener, if one is registered,
* when children are added or removed.
* @since 1.3
*/
protected class AccessibleContainerHandler
implements ContainerListener {
public void componentAdded(ContainerEvent e) {
Component c = e.getChild();
if (c != null && c instanceof Accessible) {
AccessibleAWTContainer.this.firePropertyChange(
AccessibleContext.ACCESSIBLE_CHILD_PROPERTY,
null, ((Accessible) c).getAccessibleContext());
}
}
public void componentRemoved(ContainerEvent e) {
Component c = e.getChild();
if (c != null && c instanceof Accessible) {
AccessibleAWTContainer.this.firePropertyChange(
AccessibleContext.ACCESSIBLE_CHILD_PROPERTY,
((Accessible) c).getAccessibleContext(), null);
}
}
}
/**
* Adds a PropertyChangeListener to the listener list.
*
* @param listener the PropertyChangeListener to be added
*/
public void addPropertyChangeListener(PropertyChangeListener listener) {
if (accessibleContainerHandler == null) {
accessibleContainerHandler = new AccessibleContainerHandler();
}
if (propertyListenersCount++ == 0) {
Container.this.addContainerListener(accessibleContainerHandler);
}
super.addPropertyChangeListener(listener);
}
/**
* Remove a PropertyChangeListener from the listener list.
* This removes a PropertyChangeListener that was registered
* for all properties.
*
* @param listener the PropertyChangeListener to be removed
*/
public void removePropertyChangeListener(PropertyChangeListener listener) {
if (--propertyListenersCount == 0) {
Container.this.removeContainerListener(accessibleContainerHandler);
}
super.removePropertyChangeListener(listener);
}
} // inner class AccessibleAWTContainer
/**
* Returns the <code>Accessible child contained at the local
* coordinate <code>Point, if one exists. Otherwise
* returns <code>null.
*
* @param p the point defining the top-left corner of the
* <code>Accessible, given in the coordinate space
* of the object's parent
* @return the <code>Accessible at the specified location,
* if it exists; otherwise <code>null
*/
Accessible getAccessibleAt(Point p) {
synchronized (getTreeLock()) {
if (this instanceof Accessible) {
Accessible a = (Accessible)this;
AccessibleContext ac = a.getAccessibleContext();
if (ac != null) {
AccessibleComponent acmp;
Point location;
int nchildren = ac.getAccessibleChildrenCount();
for (int i=0; i < nchildren; i++) {
a = ac.getAccessibleChild(i);
if ((a != null)) {
ac = a.getAccessibleContext();
if (ac != null) {
acmp = ac.getAccessibleComponent();
if ((acmp != null) && (acmp.isShowing())) {
location = acmp.getLocation();
Point np = new Point(p.x-location.x,
p.y-location.y);
if (acmp.contains(np)){
return a;
}
}
}
}
}
}
return (Accessible)this;
} else {
Component ret = this;
if (!this.contains(p.x,p.y)) {
ret = null;
} else {
int ncomponents = this.getComponentCount();
for (int i=0; i < ncomponents; i++) {
Component comp = this.getComponent(i);
if ((comp != null) && comp.isShowing()) {
Point location = comp.getLocation();
if (comp.contains(p.x-location.x,p.y-location.y)) {
ret = comp;
}
}
}
}
if (ret instanceof Accessible) {
return (Accessible) ret;
}
}
return null;
}
}
/**
* Returns the number of accessible children in the object. If all
* of the children of this object implement <code>Accessible,
* then this method should return the number of children of this object.
*
* @return the number of accessible children in the object
*/
int getAccessibleChildrenCount() {
synchronized (getTreeLock()) {
int count = 0;
Component[] children = this.getComponents();
for (int i = 0; i < children.length; i++) {
if (children[i] instanceof Accessible) {
count++;
}
}
return count;
}
}
/**
* Returns the nth <code>Accessible child of the object.
*
* @param i zero-based index of child
* @return the nth <code>Accessible child of the object
*/
Accessible getAccessibleChild(int i) {
synchronized (getTreeLock()) {
Component[] children = this.getComponents();
int count = 0;
for (int j = 0; j < children.length; j++) {
if (children[j] instanceof Accessible) {
if (count == i) {
return (Accessible) children[j];
} else {
count++;
}
}
}
return null;
}
}
// ************************** MIXING CODE *******************************
final void increaseComponentCount(Component c) {
synchronized (getTreeLock()) {
if (!c.isDisplayable()) {
throw new IllegalStateException(
"Peer does not exist while invoking the increaseComponentCount() method"
);
}
int addHW = 0;
int addLW = 0;
if (c instanceof Container) {
addLW = ((Container)c).numOfLWComponents;
addHW = ((Container)c).numOfHWComponents;
}
if (c.isLightweight()) {
addLW++;
} else {
addHW++;
}
for (Container cont = this; cont != null; cont = cont.getContainer()) {
cont.numOfLWComponents += addLW;
cont.numOfHWComponents += addHW;
}
}
}
final void decreaseComponentCount(Component c) {
synchronized (getTreeLock()) {
if (!c.isDisplayable()) {
throw new IllegalStateException(
"Peer does not exist while invoking the decreaseComponentCount() method"
);
}
int subHW = 0;
int subLW = 0;
if (c instanceof Container) {
subLW = ((Container)c).numOfLWComponents;
subHW = ((Container)c).numOfHWComponents;
}
if (c.isLightweight()) {
subLW++;
} else {
subHW++;
}
for (Container cont = this; cont != null; cont = cont.getContainer()) {
cont.numOfLWComponents -= subLW;
cont.numOfHWComponents -= subHW;
}
}
}
private int getTopmostComponentIndex() {
checkTreeLock();
if (getComponentCount() > 0) {
return 0;
}
return -1;
}
private int getBottommostComponentIndex() {
checkTreeLock();
if (getComponentCount() > 0) {
return getComponentCount() - 1;
}
return -1;
}
/*
* This method is overriden to handle opaque children in non-opaque
* containers.
*/
@Override
final Region getOpaqueShape() {
checkTreeLock();
if (isLightweight() && isNonOpaqueForMixing()
&& hasLightweightDescendants())
{
Region s = Region.EMPTY_REGION;
for (int index = 0; index < getComponentCount(); index++) {
Component c = getComponent(index);
if (c.isLightweight() && c.isShowing()) {
s = s.getUnion(c.getOpaqueShape());
}
}
return s.getIntersection(getNormalShape());
}
return super.getOpaqueShape();
}
final void recursiveSubtractAndApplyShape(Region shape) {
recursiveSubtractAndApplyShape(shape, getTopmostComponentIndex(), getBottommostComponentIndex());
}
final void recursiveSubtractAndApplyShape(Region shape, int fromZorder) {
recursiveSubtractAndApplyShape(shape, fromZorder, getBottommostComponentIndex());
}
final void recursiveSubtractAndApplyShape(Region shape, int fromZorder, int toZorder) {
checkTreeLock();
if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
mixingLog.fine("this = " + this +
"; shape=" + shape + "; fromZ=" + fromZorder + "; toZ=" + toZorder);
}
if (fromZorder == -1) {
return;
}
if (shape.isEmpty()) {
return;
}
// An invalid container with not-null layout should be ignored
// by the mixing code, the container will be validated later
// and the mixing code will be executed later.
if (getLayout() != null && !isValid()) {
return;
}
for (int index = fromZorder; index <= toZorder; index++) {
Component comp = getComponent(index);
if (!comp.isLightweight()) {
comp.subtractAndApplyShape(shape);
} else if (comp instanceof Container &&
((Container)comp).hasHeavyweightDescendants() && comp.isShowing()) {
((Container)comp).recursiveSubtractAndApplyShape(shape);
}
}
}
final void recursiveApplyCurrentShape() {
recursiveApplyCurrentShape(getTopmostComponentIndex(), getBottommostComponentIndex());
}
final void recursiveApplyCurrentShape(int fromZorder) {
recursiveApplyCurrentShape(fromZorder, getBottommostComponentIndex());
}
final void recursiveApplyCurrentShape(int fromZorder, int toZorder) {
checkTreeLock();
if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
mixingLog.fine("this = " + this +
"; fromZ=" + fromZorder + "; toZ=" + toZorder);
}
if (fromZorder == -1) {
return;
}
// An invalid container with not-null layout should be ignored
// by the mixing code, the container will be validated later
// and the mixing code will be executed later.
if (getLayout() != null && !isValid()) {
return;
}
for (int index = fromZorder; index <= toZorder; index++) {
Component comp = getComponent(index);
if (!comp.isLightweight()) {
comp.applyCurrentShape();
}
if (comp instanceof Container &&
((Container)comp).hasHeavyweightDescendants()) {
((Container)comp).recursiveApplyCurrentShape();
}
}
}
private void recursiveShowHeavyweightChildren() {
if (!hasHeavyweightDescendants() || !isVisible()) {
return;
}
for (int index = 0; index < getComponentCount(); index++) {
Component comp = getComponent(index);
if (comp.isLightweight()) {
if (comp instanceof Container) {
((Container)comp).recursiveShowHeavyweightChildren();
}
} else {
if (comp.isVisible()) {
ComponentPeer peer = comp.getPeer();
if (peer != null) {
peer.setVisible(true);
}
}
}
}
}
private void recursiveHideHeavyweightChildren() {
if (!hasHeavyweightDescendants()) {
return;
}
for (int index = 0; index < getComponentCount(); index++) {
Component comp = getComponent(index);
if (comp.isLightweight()) {
if (comp instanceof Container) {
((Container)comp).recursiveHideHeavyweightChildren();
}
} else {
if (comp.isVisible()) {
ComponentPeer peer = comp.getPeer();
if (peer != null) {
peer.setVisible(false);
}
}
}
}
}
private void recursiveRelocateHeavyweightChildren(Point origin) {
for (int index = 0; index < getComponentCount(); index++) {
Component comp = getComponent(index);
if (comp.isLightweight()) {
if (comp instanceof Container &&
((Container)comp).hasHeavyweightDescendants())
{
final Point newOrigin = new Point(origin);
newOrigin.translate(comp.getX(), comp.getY());
((Container)comp).recursiveRelocateHeavyweightChildren(newOrigin);
}
} else {
ComponentPeer peer = comp.getPeer();
if (peer != null) {
peer.setBounds(origin.x + comp.getX(), origin.y + comp.getY(),
comp.getWidth(), comp.getHeight(),
ComponentPeer.SET_LOCATION);
}
}
}
}
/**
* Checks if the container and its direct lightweight containers are
* visible.
*
* Consider the heavyweight container hides or shows the HW descendants
* automatically. Therefore we care of LW containers' visibility only.
*
* This method MUST be invoked under the TreeLock.
*/
final boolean isRecursivelyVisibleUpToHeavyweightContainer() {
if (!isLightweight()) {
return true;
}
for (Container cont = this;
cont != null && cont.isLightweight();
cont = cont.getContainer())
{
if (!cont.isVisible()) {
return false;
}
}
return true;
}
@Override
void mixOnShowing() {
synchronized (getTreeLock()) {
if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
mixingLog.fine("this = " + this);
}
boolean isLightweight = isLightweight();
if (isLightweight && isRecursivelyVisibleUpToHeavyweightContainer()) {
recursiveShowHeavyweightChildren();
}
if (!isMixingNeeded()) {
return;
}
if (!isLightweight || (isLightweight && hasHeavyweightDescendants())) {
recursiveApplyCurrentShape();
}
super.mixOnShowing();
}
}
@Override
void mixOnHiding(boolean isLightweight) {
synchronized (getTreeLock()) {
if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
mixingLog.fine("this = " + this +
"; isLightweight=" + isLightweight);
}
if (isLightweight) {
recursiveHideHeavyweightChildren();
}
super.mixOnHiding(isLightweight);
}
}
@Override
void mixOnReshaping() {
synchronized (getTreeLock()) {
if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
mixingLog.fine("this = " + this);
}
boolean isMixingNeeded = isMixingNeeded();
if (isLightweight() && hasHeavyweightDescendants()) {
final Point origin = new Point(getX(), getY());
for (Container cont = getContainer();
cont != null && cont.isLightweight();
cont = cont.getContainer())
{
origin.translate(cont.getX(), cont.getY());
}
recursiveRelocateHeavyweightChildren(origin);
if (!isMixingNeeded) {
return;
}
recursiveApplyCurrentShape();
}
if (!isMixingNeeded) {
return;
}
super.mixOnReshaping();
}
}
@Override
void mixOnZOrderChanging(int oldZorder, int newZorder) {
synchronized (getTreeLock()) {
if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
mixingLog.fine("this = " + this +
"; oldZ=" + oldZorder + "; newZ=" + newZorder);
}
if (!isMixingNeeded()) {
return;
}
boolean becameHigher = newZorder < oldZorder;
if (becameHigher && isLightweight() && hasHeavyweightDescendants()) {
recursiveApplyCurrentShape();
}
super.mixOnZOrderChanging(oldZorder, newZorder);
}
}
@Override
void mixOnValidating() {
synchronized (getTreeLock()) {
if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
mixingLog.fine("this = " + this);
}
if (!isMixingNeeded()) {
return;
}
if (hasHeavyweightDescendants()) {
recursiveApplyCurrentShape();
}
if (isLightweight() && isNonOpaqueForMixing()) {
subtractAndApplyShapeBelowMe();
}
super.mixOnValidating();
}
}
// ****************** END OF MIXING CODE ********************************
}
/**
* Class to manage the dispatching of MouseEvents to the lightweight descendants
* and SunDropTargetEvents to both lightweight and heavyweight descendants
* contained by a native container.
*
* NOTE: the class name is not appropriate anymore, but we cannot change it
* because we must keep serialization compatibility.
*
* @author Timothy Prinzing
*/
class LightweightDispatcher implements java.io.Serializable, AWTEventListener {
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = 5184291520170872969L;
/*
* Our own mouse event for when we're dragged over from another hw
* container
*/
private static final int LWD_MOUSE_DRAGGED_OVER = 1500;
private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.LightweightDispatcher");
LightweightDispatcher(Container nativeContainer) {
this.nativeContainer = nativeContainer;
mouseEventTarget = null;
eventMask = 0;
}
/*
* Clean up any resources allocated when dispatcher was created;
* should be called from Container.removeNotify
*/
void dispose() {
//System.out.println("Disposing lw dispatcher");
stopListeningForOtherDrags();
mouseEventTarget = null;
targetLastEntered = null;
targetLastEnteredDT = null;
}
/**
* Enables events to subcomponents.
*/
void enableEvents(long events) {
eventMask |= events;
}
/**
* Dispatches an event to a sub-component if necessary, and
* returns whether or not the event was forwarded to a
* sub-component.
*
* @param e the event
*/
boolean dispatchEvent(AWTEvent e) {
boolean ret = false;
/*
* Fix for BugTraq Id 4389284.
* Dispatch SunDropTargetEvents regardless of eventMask value.
* Do not update cursor on dispatching SunDropTargetEvents.
*/
if (e instanceof SunDropTargetEvent) {
SunDropTargetEvent sdde = (SunDropTargetEvent) e;
ret = processDropTargetEvent(sdde);
} else {
if (e instanceof MouseEvent && (eventMask & MOUSE_MASK) != 0) {
MouseEvent me = (MouseEvent) e;
ret = processMouseEvent(me);
}
if (e.getID() == MouseEvent.MOUSE_MOVED) {
nativeContainer.updateCursorImmediately();
}
}
return ret;
}
/* This method effectively returns whether or not a mouse button was down
* just BEFORE the event happened. A better method name might be
* wasAMouseButtonDownBeforeThisEvent().
*/
private boolean isMouseGrab(MouseEvent e) {
int modifiers = e.getModifiersEx();
if(e.getID() == MouseEvent.MOUSE_PRESSED
|| e.getID() == MouseEvent.MOUSE_RELEASED)
{
switch (e.getButton()) {
case MouseEvent.BUTTON1:
modifiers ^= InputEvent.BUTTON1_DOWN_MASK;
break;
case MouseEvent.BUTTON2:
modifiers ^= InputEvent.BUTTON2_DOWN_MASK;
break;
case MouseEvent.BUTTON3:
modifiers ^= InputEvent.BUTTON3_DOWN_MASK;
break;
}
}
/* modifiers now as just before event */
return ((modifiers & (InputEvent.BUTTON1_DOWN_MASK
| InputEvent.BUTTON2_DOWN_MASK
| InputEvent.BUTTON3_DOWN_MASK)) != 0);
}
/**
* This method attempts to distribute a mouse event to a lightweight
* component. It tries to avoid doing any unnecessary probes down
* into the component tree to minimize the overhead of determining
* where to route the event, since mouse movement events tend to
* come in large and frequent amounts.
*/
private boolean processMouseEvent(MouseEvent e) {
int id = e.getID();
Component mouseOver = // sensitive to mouse events
nativeContainer.getMouseEventTarget(e.getX(), e.getY(),
Container.INCLUDE_SELF);
trackMouseEnterExit(mouseOver, e);
// 4508327 : MOUSE_CLICKED should only go to the recipient of
// the accompanying MOUSE_PRESSED, so don't reset mouseEventTarget on a
// MOUSE_CLICKED.
if (!isMouseGrab(e) && id != MouseEvent.MOUSE_CLICKED) {
mouseEventTarget = (mouseOver != nativeContainer) ? mouseOver: null;
isCleaned = false;
}
if (mouseEventTarget != null) {
switch (id) {
case MouseEvent.MOUSE_ENTERED:
case MouseEvent.MOUSE_EXITED:
break;
case MouseEvent.MOUSE_PRESSED:
retargetMouseEvent(mouseEventTarget, id, e);
break;
case MouseEvent.MOUSE_RELEASED:
retargetMouseEvent(mouseEventTarget, id, e);
break;
case MouseEvent.MOUSE_CLICKED:
// 4508327: MOUSE_CLICKED should never be dispatched to a Component
// other than that which received the MOUSE_PRESSED event. If the
// mouse is now over a different Component, don't dispatch the event.
// The previous fix for a similar problem was associated with bug
// 4155217.
if (mouseOver == mouseEventTarget) {
retargetMouseEvent(mouseOver, id, e);
}
break;
case MouseEvent.MOUSE_MOVED:
retargetMouseEvent(mouseEventTarget, id, e);
break;
case MouseEvent.MOUSE_DRAGGED:
if (isMouseGrab(e)) {
retargetMouseEvent(mouseEventTarget, id, e);
}
break;
case MouseEvent.MOUSE_WHEEL:
// This may send it somewhere that doesn't have MouseWheelEvents
// enabled. In this case, Component.dispatchEventImpl() will
// retarget the event to a parent that DOES have the events enabled.
if (eventLog.isLoggable(PlatformLogger.Level.FINEST) && (mouseOver != null)) {
eventLog.finest("retargeting mouse wheel to " +
mouseOver.getName() + ", " +
mouseOver.getClass());
}
retargetMouseEvent(mouseOver, id, e);
break;
}
//Consuming of wheel events is implemented in "retargetMouseEvent".
if (id != MouseEvent.MOUSE_WHEEL) {
e.consume();
}
} else if (isCleaned && id != MouseEvent.MOUSE_WHEEL) {
//After mouseEventTarget was removed and cleaned should consume all events
//until new mouseEventTarget is found
e.consume();
}
return e.isConsumed();
}
private boolean processDropTargetEvent(SunDropTargetEvent e) {
int id = e.getID();
int x = e.getX();
int y = e.getY();
/*
* Fix for BugTraq ID 4395290.
* It is possible that SunDropTargetEvent's Point is outside of the
* native container bounds. In this case we truncate coordinates.
*/
if (!nativeContainer.contains(x, y)) {
final Dimension d = nativeContainer.getSize();
if (d.width <= x) {
x = d.width - 1;
} else if (x < 0) {
x = 0;
}
if (d.height <= y) {
y = d.height - 1;
} else if (y < 0) {
y = 0;
}
}
Component mouseOver = // not necessarily sensitive to mouse events
nativeContainer.getDropTargetEventTarget(x, y,
Container.INCLUDE_SELF);
trackMouseEnterExit(mouseOver, e);
if (mouseOver != nativeContainer && mouseOver != null) {
switch (id) {
case SunDropTargetEvent.MOUSE_ENTERED:
case SunDropTargetEvent.MOUSE_EXITED:
break;
default:
retargetMouseEvent(mouseOver, id, e);
e.consume();
break;
}
}
return e.isConsumed();
}
/*
* Generates dnd enter/exit events as mouse moves over lw components
* @param targetOver Target mouse is over (including native container)
* @param e SunDropTarget mouse event in native container
*/
private void trackDropTargetEnterExit(Component targetOver, MouseEvent e) {
int id = e.getID();
if (id == MouseEvent.MOUSE_ENTERED && isMouseDTInNativeContainer) {
// This can happen if a lightweight component which initiated the
// drag has an associated drop target. MOUSE_ENTERED comes when the
// mouse is in the native container already. To propagate this event
// properly we should null out targetLastEntered.
targetLastEnteredDT = null;
} else if (id == MouseEvent.MOUSE_ENTERED) {
isMouseDTInNativeContainer = true;
} else if (id == MouseEvent.MOUSE_EXITED) {
isMouseDTInNativeContainer = false;
}
targetLastEnteredDT = retargetMouseEnterExit(targetOver, e,
targetLastEnteredDT,
isMouseDTInNativeContainer);
}
/*
* Generates enter/exit events as mouse moves over lw components
* @param targetOver Target mouse is over (including native container)
* @param e Mouse event in native container
*/
private void trackMouseEnterExit(Component targetOver, MouseEvent e) {
if (e instanceof SunDropTargetEvent) {
trackDropTargetEnterExit(targetOver, e);
return;
}
int id = e.getID();
if ( id != MouseEvent.MOUSE_EXITED &&
id != MouseEvent.MOUSE_DRAGGED &&
id != LWD_MOUSE_DRAGGED_OVER &&
!isMouseInNativeContainer) {
// any event but an exit or drag means we're in the native container
isMouseInNativeContainer = true;
startListeningForOtherDrags();
} else if (id == MouseEvent.MOUSE_EXITED) {
isMouseInNativeContainer = false;
stopListeningForOtherDrags();
}
targetLastEntered = retargetMouseEnterExit(targetOver, e,
targetLastEntered,
isMouseInNativeContainer);
}
private Component retargetMouseEnterExit(Component targetOver, MouseEvent e,
Component lastEntered,
boolean inNativeContainer) {
int id = e.getID();
Component targetEnter = inNativeContainer ? targetOver : null;
if (lastEntered != targetEnter) {
if (lastEntered != null) {
retargetMouseEvent(lastEntered, MouseEvent.MOUSE_EXITED, e);
}
if (id == MouseEvent.MOUSE_EXITED) {
// consume native exit event if we generate one
e.consume();
}
if (targetEnter != null) {
retargetMouseEvent(targetEnter, MouseEvent.MOUSE_ENTERED, e);
}
if (id == MouseEvent.MOUSE_ENTERED) {
// consume native enter event if we generate one
e.consume();
}
}
return targetEnter;
}
/*
* Listens to global mouse drag events so even drags originating
* from other heavyweight containers will generate enter/exit
* events in this container
*/
private void startListeningForOtherDrags() {
//System.out.println("Adding AWTEventListener");
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Object>() {
public Object run() {
nativeContainer.getToolkit().addAWTEventListener(
LightweightDispatcher.this,
AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASK);
return null;
}
}
);
}
private void stopListeningForOtherDrags() {
//System.out.println("Removing AWTEventListener");
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Object>() {
public Object run() {
nativeContainer.getToolkit().removeAWTEventListener(LightweightDispatcher.this);
return null;
}
}
);
}
/*
* (Implementation of AWTEventListener)
* Listen for drag events posted in other hw components so we can
* track enter/exit regardless of where a drag originated
*/
public void eventDispatched(AWTEvent e) {
boolean isForeignDrag = (e instanceof MouseEvent) &&
!(e instanceof SunDropTargetEvent) &&
(e.id == MouseEvent.MOUSE_DRAGGED) &&
(e.getSource() != nativeContainer);
if (!isForeignDrag) {
// only interested in drags from other hw components
return;
}
MouseEvent srcEvent = (MouseEvent)e;
MouseEvent me;
synchronized (nativeContainer.getTreeLock()) {
Component srcComponent = srcEvent.getComponent();
// component may have disappeared since drag event posted
// (i.e. Swing hierarchical menus)
if ( !srcComponent.isShowing() ) {
return;
}
// see 5083555
// check if srcComponent is in any modal blocked window
Component c = nativeContainer;
while ((c != null) && !(c instanceof Window)) {
c = c.getParent_NoClientCode();
}
if ((c == null) || ((Window)c).isModalBlocked()) {
return;
}
//
// create an internal 'dragged-over' event indicating
// we are being dragged over from another hw component
//
me = new MouseEvent(nativeContainer,
LWD_MOUSE_DRAGGED_OVER,
srcEvent.getWhen(),
srcEvent.getModifiersEx() | srcEvent.getModifiers(),
srcEvent.getX(),
srcEvent.getY(),
srcEvent.getXOnScreen(),
srcEvent.getYOnScreen(),
srcEvent.getClickCount(),
srcEvent.isPopupTrigger(),
srcEvent.getButton());
((AWTEvent)srcEvent).copyPrivateDataInto(me);
// translate coordinates to this native container
final Point ptSrcOrigin = srcComponent.getLocationOnScreen();
if (AppContext.getAppContext() != nativeContainer.appContext) {
final MouseEvent mouseEvent = me;
Runnable r = new Runnable() {
public void run() {
if (!nativeContainer.isShowing() ) {
return;
}
Point ptDstOrigin = nativeContainer.getLocationOnScreen();
mouseEvent.translatePoint(ptSrcOrigin.x - ptDstOrigin.x,
ptSrcOrigin.y - ptDstOrigin.y );
Component targetOver =
nativeContainer.getMouseEventTarget(mouseEvent.getX(),
mouseEvent.getY(),
Container.INCLUDE_SELF);
trackMouseEnterExit(targetOver, mouseEvent);
}
};
SunToolkit.executeOnEventHandlerThread(nativeContainer, r);
return;
} else {
if (!nativeContainer.isShowing() ) {
return;
}
Point ptDstOrigin = nativeContainer.getLocationOnScreen();
me.translatePoint( ptSrcOrigin.x - ptDstOrigin.x, ptSrcOrigin.y - ptDstOrigin.y );
}
}
//System.out.println("Track event: " + me);
// feed the 'dragged-over' event directly to the enter/exit
// code (not a real event so don't pass it to dispatchEvent)
Component targetOver =
nativeContainer.getMouseEventTarget(me.getX(), me.getY(),
Container.INCLUDE_SELF);
trackMouseEnterExit(targetOver, me);
}
/**
* Sends a mouse event to the current mouse event recipient using
* the given event (sent to the windowed host) as a srcEvent. If
* the mouse event target is still in the component tree, the
* coordinates of the event are translated to those of the target.
* If the target has been removed, we don't bother to send the
* message.
*/
void retargetMouseEvent(Component target, int id, MouseEvent e) {
if (target == null) {
return; // mouse is over another hw component or target is disabled
}
int x = e.getX(), y = e.getY();
Component component;
for(component = target;
component != null && component != nativeContainer;
component = component.getParent()) {
x -= component.x;
y -= component.y;
}
MouseEvent retargeted;
if (component != null) {
if (e instanceof SunDropTargetEvent) {
retargeted = new SunDropTargetEvent(target,
id,
x,
y,
((SunDropTargetEvent)e).getDispatcher());
} else if (id == MouseEvent.MOUSE_WHEEL) {
retargeted = new MouseWheelEvent(target,
id,
e.getWhen(),
e.getModifiersEx() | e.getModifiers(),
x,
y,
e.getXOnScreen(),
e.getYOnScreen(),
e.getClickCount(),
e.isPopupTrigger(),
((MouseWheelEvent)e).getScrollType(),
((MouseWheelEvent)e).getScrollAmount(),
((MouseWheelEvent)e).getWheelRotation(),
((MouseWheelEvent)e).getPreciseWheelRotation());
}
else {
retargeted = new MouseEvent(target,
id,
e.getWhen(),
e.getModifiersEx() | e.getModifiers(),
x,
y,
e.getXOnScreen(),
e.getYOnScreen(),
e.getClickCount(),
e.isPopupTrigger(),
e.getButton());
}
((AWTEvent)e).copyPrivateDataInto(retargeted);
if (target == nativeContainer) {
// avoid recursively calling LightweightDispatcher...
((Container)target).dispatchEventToSelf(retargeted);
} else {
assert AppContext.getAppContext() == target.appContext;
if (nativeContainer.modalComp != null) {
if (((Container)nativeContainer.modalComp).isAncestorOf(target)) {
target.dispatchEvent(retargeted);
} else {
e.consume();
}
} else {
target.dispatchEvent(retargeted);
}
}
if (id == MouseEvent.MOUSE_WHEEL && retargeted.isConsumed()) {
//An exception for wheel bubbling to the native system.
//In "processMouseEvent" total event consuming for wheel events is skipped.
//Protection from bubbling of Java-accepted wheel events.
e.consume();
}
}
}
// --- member variables -------------------------------
/**
* The windowed container that might be hosting events for
* subcomponents.
*/
private Container nativeContainer;
/**
* This variable is not used, but kept for serialization compatibility
*/
private Component focus;
/**
* The current subcomponent being hosted by this windowed
* component that has events being forwarded to it. If this
* is null, there are currently no events being forwarded to
* a subcomponent.
*/
private transient Component mouseEventTarget;
/**
* The last component entered by the {@code MouseEvent}.
*/
private transient Component targetLastEntered;
/**
* The last component entered by the {@code SunDropTargetEvent}.
*/
private transient Component targetLastEnteredDT;
/**
* Indicates whether {@code mouseEventTarget} was removed and nulled
*/
private transient boolean isCleaned;
/**
* Is the mouse over the native container.
*/
private transient boolean isMouseInNativeContainer = false;
/**
* Is DnD over the native container.
*/
private transient boolean isMouseDTInNativeContainer = false;
/**
* This variable is not used, but kept for serialization compatibility
*/
private Cursor nativeCursor;
/**
* The event mask for contained lightweight components. Lightweight
* components need a windowed container to host window-related
* events. This separate mask indicates events that have been
* requested by contained lightweight components without effecting
* the mask of the windowed component itself.
*/
private long eventMask;
/**
* The kind of events routed to lightweight components from windowed
* hosts.
*/
private static final long PROXY_EVENT_MASK =
AWTEvent.FOCUS_EVENT_MASK |
AWTEvent.KEY_EVENT_MASK |
AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASK |
AWTEvent.MOUSE_WHEEL_EVENT_MASK;
private static final long MOUSE_MASK =
AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASK |
AWTEvent.MOUSE_WHEEL_EVENT_MASK;
void removeReferences(Component removedComponent) {
if (mouseEventTarget == removedComponent) {
isCleaned = true;
mouseEventTarget = null;
}
if (targetLastEntered == removedComponent) {
targetLastEntered = null;
}
if (targetLastEnteredDT == removedComponent) {
targetLastEnteredDT = null;
}
}
}
Here is a short list of links related to this Java Container.java source code file:
Java example source code file (Container.java)
The Container.java Java example source code/* * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt; import java.awt.dnd.DropTarget; import java.awt.event.*; import java.awt.peer.ContainerPeer; import java.awt.peer.ComponentPeer; import java.awt.peer.LightweightPeer; import java.beans.PropertyChangeListener; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.io.PrintStream; import java.io.PrintWriter; import java.security.AccessController; import java.util.EventListener; import java.util.HashSet; import java.util.Set; import javax.accessibility.*; import sun.util.logging.PlatformLogger; import sun.awt.AppContext; import sun.awt.AWTAccessor; import sun.awt.CausedFocusEvent; import sun.awt.PeerEvent; import sun.awt.SunToolkit; import sun.awt.dnd.SunDropTargetEvent; import sun.java2d.pipe.Region; import sun.security.action.GetBooleanAction; /** * A generic Abstract Window Toolkit(AWT) container object is a component * that can contain other AWT components. * <p> * Components added to a container are tracked in a list. The order * of the list will define the components' front-to-back stacking order * within the container. If no index is specified when adding a * component to a container, it will be added to the end of the list * (and hence to the bottom of the stacking order). * <p> * <b>Note: For details on the focus subsystem, see * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html"> * How to Use the Focus Subsystem</a>, * a section in <em>The Java Tutorial, and the * <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification * for more information. * * @author Arthur van Hoff * @author Sami Shaio * @see #add(java.awt.Component, int) * @see #getComponent(int) * @see LayoutManager * @since JDK1.0 */ public class Container extends Component { private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.Container"); private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.Container"); private static final Component[] EMPTY_ARRAY = new Component[0]; /** * The components in this container. * @see #add * @see #getComponents */ private java.util.List<Component> component = new java.util.ArrayList* * If no such listeners exist, this method returns an empty array. * * @param listenerType the type of listeners requested; this parameter * should specify an interface that descends from * <code>java.util.EventListener * @return an array of all objects registered as * <code>FooListeners on this container, * or an empty array if no such listeners have been added * @exception ClassCastException if <code>listenerType * doesn't specify a class or interface that implements * <code>java.util.EventListener * @exception NullPointerException if {@code listenerType} is {@code null} * * @see #getContainerListeners * * @since 1.3 */ public <T extends EventListener> T[] getListeners(Class null
* the behavior is unspecified and may result in an
* exception.
*
* @param e the event
*/
protected void processEvent(AWTEvent e) {
if (e instanceof ContainerEvent) {
processContainerEvent((ContainerEvent)e);
return;
}
super.processEvent(e);
}
/**
* Processes container events occurring on this container by
* dispatching them to any registered ContainerListener objects.
* NOTE: This method will not be called unless container events
* are enabled for this component; this happens when one of the
* following occurs:
* <ul>
* <li>A ContainerListener object is registered via
* <code>addContainerListener
* <li>Container events are enabled via enableEvents
* </ul>
* <p>Note that if the event parameter is null
* the behavior is unspecified and may result in an
* exception.
*
* @param e the container event
* @see Component#enableEvents
*/
protected void processContainerEvent(ContainerEvent e) {
ContainerListener listener = containerListener;
if (listener != null) {
switch(e.getID()) {
case ContainerEvent.COMPONENT_ADDED:
listener.componentAdded(e);
break;
case ContainerEvent.COMPONENT_REMOVED:
listener.componentRemoved(e);
break;
}
}
}
/*
* Dispatches an event to this component or one of its sub components.
* Create ANCESTOR_RESIZED and ANCESTOR_MOVED events in response to
* COMPONENT_RESIZED and COMPONENT_MOVED events. We have to do this
* here instead of in processComponentEvent because ComponentEvents
* may not be enabled for this Container.
* @param e the event
*/
void dispatchEventImpl(AWTEvent e) {
if ((dispatcher != null) && dispatcher.dispatchEvent(e)) {
// event was sent to a lightweight component. The
// native-produced event sent to the native container
// must be properly disposed of by the peer, so it
// gets forwarded. If the native host has been removed
// as a result of the sending the lightweight event,
// the peer reference will be null.
e.consume();
if (peer != null) {
peer.handleEvent(e);
}
return;
}
super.dispatchEventImpl(e);
synchronized (getTreeLock()) {
switch (e.getID()) {
case ComponentEvent.COMPONENT_RESIZED:
createChildHierarchyEvents(HierarchyEvent.ANCESTOR_RESIZED, 0,
Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
break;
case ComponentEvent.COMPONENT_MOVED:
createChildHierarchyEvents(HierarchyEvent.ANCESTOR_MOVED, 0,
Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
break;
default:
break;
}
}
}
/*
* Dispatches an event to this component, without trying to forward
* it to any subcomponents
* @param e the event
*/
void dispatchEventToSelf(AWTEvent e) {
super.dispatchEventImpl(e);
}
/**
* Fetchs the top-most (deepest) lightweight component that is interested
* in receiving mouse events.
*/
Component getMouseEventTarget(int x, int y, boolean includeSelf) {
return getMouseEventTarget(x, y, includeSelf,
MouseEventTargetFilter.FILTER,
!SEARCH_HEAVYWEIGHTS);
}
/**
* Fetches the top-most (deepest) component to receive SunDropTargetEvents.
*/
Component getDropTargetEventTarget(int x, int y, boolean includeSelf) {
return getMouseEventTarget(x, y, includeSelf,
DropTargetEventTargetFilter.FILTER,
SEARCH_HEAVYWEIGHTS);
}
/**
* A private version of getMouseEventTarget which has two additional
* controllable behaviors. This method searches for the top-most
* descendant of this container that contains the given coordinates
* and is accepted by the given filter. The search will be constrained to
* lightweight descendants if the last argument is <code>false.
*
* @param filter EventTargetFilter instance to determine whether the
* given component is a valid target for this event.
* @param searchHeavyweights if <code>false, the method
* will bypass heavyweight components during the search.
*/
private Component getMouseEventTarget(int x, int y, boolean includeSelf,
EventTargetFilter filter,
boolean searchHeavyweights) {
Component comp = null;
if (searchHeavyweights) {
comp = getMouseEventTargetImpl(x, y, includeSelf, filter,
SEARCH_HEAVYWEIGHTS,
searchHeavyweights);
}
if (comp == null || comp == this) {
comp = getMouseEventTargetImpl(x, y, includeSelf, filter,
!SEARCH_HEAVYWEIGHTS,
searchHeavyweights);
}
return comp;
}
/**
* A private version of getMouseEventTarget which has three additional
* controllable behaviors. This method searches for the top-most
* descendant of this container that contains the given coordinates
* and is accepted by the given filter. The search will be constrained to
* descendants of only lightweight children or only heavyweight children
* of this container depending on searchHeavyweightChildren. The search will
* be constrained to only lightweight descendants of the searched children
* of this container if searchHeavyweightDescendants is <code>false.
*
* @param filter EventTargetFilter instance to determine whether the
* selected component is a valid target for this event.
* @param searchHeavyweightChildren if <code>true, the method
* will bypass immediate lightweight children during the search.
* If <code>false, the methods will bypass immediate
* heavyweight children during the search.
* @param searchHeavyweightDescendants if <code>false, the method
* will bypass heavyweight descendants which are not immediate
* children during the search. If <code>true, the method
* will traverse both lightweight and heavyweight descendants during
* the search.
*/
private Component getMouseEventTargetImpl(int x, int y, boolean includeSelf,
EventTargetFilter filter,
boolean searchHeavyweightChildren,
boolean searchHeavyweightDescendants) {
synchronized (getTreeLock()) {
for (int i = 0; i < component.size(); i++) {
Component comp = component.get(i);
if (comp != null && comp.visible &&
((!searchHeavyweightChildren &&
comp.peer instanceof LightweightPeer) ||
(searchHeavyweightChildren &&
!(comp.peer instanceof LightweightPeer))) &&
comp.contains(x - comp.x, y - comp.y)) {
// found a component that intersects the point, see if there
// is a deeper possibility.
if (comp instanceof Container) {
Container child = (Container) comp;
Component deeper = child.getMouseEventTarget(
x - child.x,
y - child.y,
includeSelf,
filter,
searchHeavyweightDescendants);
if (deeper != null) {
return deeper;
}
} else {
if (filter.accept(comp)) {
// there isn't a deeper target, but this component
// is a target
return comp;
}
}
}
}
boolean isPeerOK;
boolean isMouseOverMe;
isPeerOK = (peer instanceof LightweightPeer) || includeSelf;
isMouseOverMe = contains(x,y);
// didn't find a child target, return this component if it's
// a possible target
if (isMouseOverMe && isPeerOK && filter.accept(this)) {
return this;
}
// no possible target
return null;
}
}
static interface EventTargetFilter {
boolean accept(final Component comp);
}
static class MouseEventTargetFilter implements EventTargetFilter {
static final EventTargetFilter FILTER = new MouseEventTargetFilter();
private MouseEventTargetFilter() {}
public boolean accept(final Component comp) {
return (comp.eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0
|| (comp.eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0
|| (comp.eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0
|| comp.mouseListener != null
|| comp.mouseMotionListener != null
|| comp.mouseWheelListener != null;
}
}
static class DropTargetEventTargetFilter implements EventTargetFilter {
static final EventTargetFilter FILTER = new DropTargetEventTargetFilter();
private DropTargetEventTargetFilter() {}
public boolean accept(final Component comp) {
DropTarget dt = comp.getDropTarget();
return dt != null && dt.isActive();
}
}
/**
* This is called by lightweight components that want the containing
* windowed parent to enable some kind of events on their behalf.
* This is needed for events that are normally only dispatched to
* windows to be accepted so that they can be forwarded downward to
* the lightweight component that has enabled them.
*/
void proxyEnableEvents(long events) {
if (peer instanceof LightweightPeer) {
// this container is lightweight.... continue sending it
// upward.
if (parent != null) {
parent.proxyEnableEvents(events);
}
} else {
// This is a native container, so it needs to host
// one of it's children. If this function is called before
// a peer has been created we don't yet have a dispatcher
// because it has not yet been determined if this instance
// is lightweight.
if (dispatcher != null) {
dispatcher.enableEvents(events);
}
}
}
/**
* @deprecated As of JDK version 1.1,
* replaced by <code>dispatchEvent(AWTEvent e)
*/
@Deprecated
public void deliverEvent(Event e) {
Component comp = getComponentAt(e.x, e.y);
if ((comp != null) && (comp != this)) {
e.translate(-comp.x, -comp.y);
comp.deliverEvent(e);
} else {
postEvent(e);
}
}
/**
* Locates the component that contains the x,y position. The
* top-most child component is returned in the case where there
* is overlap in the components. This is determined by finding
* the component closest to the index 0 that claims to contain
* the given point via Component.contains(), except that Components
* which have native peers take precedence over those which do not
* (i.e., lightweight Components).
*
* @param x the <i>x coordinate
* @param y the <i>y coordinate
* @return null if the component does not contain the position.
* If there is no child component at the requested point and the
* point is within the bounds of the container the container itself
* is returned; otherwise the top-most child is returned.
* @see Component#contains
* @since JDK1.1
*/
public Component getComponentAt(int x, int y) {
return locate(x, y);
}
/**
* @deprecated As of JDK version 1.1,
* replaced by <code>getComponentAt(int, int).
*/
@Deprecated
public Component locate(int x, int y) {
if (!contains(x, y)) {
return null;
}
synchronized (getTreeLock()) {
// Two passes: see comment in sun.awt.SunGraphicsCallback
for (int i = 0; i < component.size(); i++) {
Component comp = component.get(i);
if (comp != null &&
!(comp.peer instanceof LightweightPeer)) {
if (comp.contains(x - comp.x, y - comp.y)) {
return comp;
}
}
}
for (int i = 0; i < component.size(); i++) {
Component comp = component.get(i);
if (comp != null &&
comp.peer instanceof LightweightPeer) {
if (comp.contains(x - comp.x, y - comp.y)) {
return comp;
}
}
}
}
return this;
}
/**
* Gets the component that contains the specified point.
* @param p the point.
* @return returns the component that contains the point,
* or <code>null if the component does
* not contain the point.
* @see Component#contains
* @since JDK1.1
*/
public Component getComponentAt(Point p) {
return getComponentAt(p.x, p.y);
}
/**
* Returns the position of the mouse pointer in this <code>Container's
* coordinate space if the <code>Container is under the mouse pointer,
* otherwise returns <code>null.
* This method is similar to {@link Component#getMousePosition()} with the exception
* that it can take the <code>Container's children into account.
* If <code>allowChildren is false , this method will return
* a non-null value only if the mouse pointer is above the <code>Container
* directly, not above the part obscured by children.
* If <code>allowChildren is true , this method returns
* a non-null value if the mouse pointer is above <code>Container or any
* of its descendants.
*
* @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true
* @param allowChildren true if children should be taken into account
* @see Component#getMousePosition
* @return mouse coordinates relative to this <code>Component, or null
* @since 1.5
*/
public Point getMousePosition(boolean allowChildren) throws HeadlessException {
if (GraphicsEnvironment.isHeadless()) {
throw new HeadlessException();
}
PointerInfo pi = java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<PointerInfo>() {
public PointerInfo run() {
return MouseInfo.getPointerInfo();
}
}
);
synchronized (getTreeLock()) {
Component inTheSameWindow = findUnderMouseInWindow(pi);
if (isSameOrAncestorOf(inTheSameWindow, allowChildren)) {
return pointRelativeToComponent(pi.getLocation());
}
return null;
}
}
boolean isSameOrAncestorOf(Component comp, boolean allowChildren) {
return this == comp || (allowChildren && isParentOf(comp));
}
/**
* Locates the visible child component that contains the specified
* position. The top-most child component is returned in the case
* where there is overlap in the components. If the containing child
* component is a Container, this method will continue searching for
* the deepest nested child component. Components which are not
* visible are ignored during the search.<p>
*
* The findComponentAt method is different from getComponentAt in
* that getComponentAt only searches the Container's immediate
* children; if the containing component is a Container,
* findComponentAt will search that child to find a nested component.
*
* @param x the <i>x coordinate
* @param y the <i>y coordinate
* @return null if the component does not contain the position.
* If there is no child component at the requested point and the
* point is within the bounds of the container the container itself
* is returned.
* @see Component#contains
* @see #getComponentAt
* @since 1.2
*/
public Component findComponentAt(int x, int y) {
return findComponentAt(x, y, true);
}
/**
* Private version of findComponentAt which has a controllable
* behavior. Setting 'ignoreEnabled' to 'false' bypasses disabled
* Components during the search. This behavior is used by the
* lightweight cursor support in sun.awt.GlobalCursorManager.
*
* The addition of this feature is temporary, pending the
* adoption of new, public API which exports this feature.
*/
final Component findComponentAt(int x, int y, boolean ignoreEnabled) {
synchronized (getTreeLock()) {
if (isRecursivelyVisible()){
return findComponentAtImpl(x, y, ignoreEnabled);
}
}
return null;
}
final Component findComponentAtImpl(int x, int y, boolean ignoreEnabled){
checkTreeLock();
if (!(contains(x, y) && visible && (ignoreEnabled || enabled))) {
return null;
}
// Two passes: see comment in sun.awt.SunGraphicsCallback
for (int i = 0; i < component.size(); i++) {
Component comp = component.get(i);
if (comp != null &&
!(comp.peer instanceof LightweightPeer)) {
if (comp instanceof Container) {
comp = ((Container)comp).findComponentAtImpl(x - comp.x,
y - comp.y,
ignoreEnabled);
} else {
comp = comp.getComponentAt(x - comp.x, y - comp.y);
}
if (comp != null && comp.visible &&
(ignoreEnabled || comp.enabled))
{
return comp;
}
}
}
for (int i = 0; i < component.size(); i++) {
Component comp = component.get(i);
if (comp != null &&
comp.peer instanceof LightweightPeer) {
if (comp instanceof Container) {
comp = ((Container)comp).findComponentAtImpl(x - comp.x,
y - comp.y,
ignoreEnabled);
} else {
comp = comp.getComponentAt(x - comp.x, y - comp.y);
}
if (comp != null && comp.visible &&
(ignoreEnabled || comp.enabled))
{
return comp;
}
}
}
return this;
}
/**
* Locates the visible child component that contains the specified
* point. The top-most child component is returned in the case
* where there is overlap in the components. If the containing child
* component is a Container, this method will continue searching for
* the deepest nested child component. Components which are not
* visible are ignored during the search.<p>
*
* The findComponentAt method is different from getComponentAt in
* that getComponentAt only searches the Container's immediate
* children; if the containing component is a Container,
* findComponentAt will search that child to find a nested component.
*
* @param p the point.
* @return null if the component does not contain the position.
* If there is no child component at the requested point and the
* point is within the bounds of the container the container itself
* is returned.
* @throws NullPointerException if {@code p} is {@code null}
* @see Component#contains
* @see #getComponentAt
* @since 1.2
*/
public Component findComponentAt(Point p) {
return findComponentAt(p.x, p.y);
}
/**
* Makes this Container displayable by connecting it to
* a native screen resource. Making a container displayable will
* cause all of its children to be made displayable.
* This method is called internally by the toolkit and should
* not be called directly by programs.
* @see Component#isDisplayable
* @see #removeNotify
*/
public void addNotify() {
synchronized (getTreeLock()) {
// addNotify() on the children may cause proxy event enabling
// on this instance, so we first call super.addNotify() and
// possibly create an lightweight event dispatcher before calling
// addNotify() on the children which may be lightweight.
super.addNotify();
if (! (peer instanceof LightweightPeer)) {
dispatcher = new LightweightDispatcher(this);
}
// We shouldn't use iterator because of the Swing menu
// implementation specifics:
// the menu is being assigned as a child to JLayeredPane
// instead of particular component so always affect
// collection of component if menu is becoming shown or hidden.
for (int i = 0; i < component.size(); i++) {
component.get(i).addNotify();
}
}
}
/**
* Makes this Container undisplayable by removing its connection
* to its native screen resource. Making a container undisplayable
* will cause all of its children to be made undisplayable.
* This method is called by the toolkit internally and should
* not be called directly by programs.
* @see Component#isDisplayable
* @see #addNotify
*/
public void removeNotify() {
synchronized (getTreeLock()) {
// We shouldn't use iterator because of the Swing menu
// implementation specifics:
// the menu is being assigned as a child to JLayeredPane
// instead of particular component so always affect
// collection of component if menu is becoming shown or hidden.
for (int i = component.size()-1 ; i >= 0 ; i--) {
Component comp = component.get(i);
if (comp != null) {
// Fix for 6607170.
// We want to suppress focus change on disposal
// of the focused component. But because of focus
// is asynchronous, we should suppress focus change
// on every component in case it receives native focus
// in the process of disposal.
comp.setAutoFocusTransferOnDisposal(false);
comp.removeNotify();
comp.setAutoFocusTransferOnDisposal(true);
}
}
// If some of the children had focus before disposal then it still has.
// Auto-transfer focus to the next (or previous) component if auto-transfer
// is enabled.
if (containsFocus() && KeyboardFocusManager.isAutoFocusTransferEnabledFor(this)) {
if (!transferFocus(false)) {
transferFocusBackward(true);
}
}
if ( dispatcher != null ) {
dispatcher.dispose();
dispatcher = null;
}
super.removeNotify();
}
}
/**
* Checks if the component is contained in the component hierarchy of
* this container.
* @param c the component
* @return <code>true if it is an ancestor;
* <code>false otherwise.
* @since JDK1.1
*/
public boolean isAncestorOf(Component c) {
Container p;
if (c == null || ((p = c.getParent()) == null)) {
return false;
}
while (p != null) {
if (p == this) {
return true;
}
p = p.getParent();
}
return false;
}
/*
* The following code was added to support modal JInternalFrames
* Unfortunately this code has to be added here so that we can get access to
* some private AWT classes like SequencedEvent.
*
* The native container of the LW component has this field set
* to tell it that it should block Mouse events for all LW
* children except for the modal component.
*
* In the case of nested Modal components, we store the previous
* modal component in the new modal components value of modalComp;
*/
transient Component modalComp;
transient AppContext modalAppContext;
private void startLWModal() {
// Store the app context on which this component is being shown.
// Event dispatch thread of this app context will be sleeping until
// we wake it by any event from hideAndDisposeHandler().
modalAppContext = AppContext.getAppContext();
// keep the KeyEvents from being dispatched
// until the focus has been transfered
long time = Toolkit.getEventQueue().getMostRecentKeyEventTime();
Component predictedFocusOwner = (Component.isInstanceOf(this, "javax.swing.JInternalFrame")) ? ((javax.swing.JInternalFrame)(this)).getMostRecentFocusOwner() : null;
if (predictedFocusOwner != null) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().
enqueueKeyEvents(time, predictedFocusOwner);
}
// We have two mechanisms for blocking: 1. If we're on the
// EventDispatchThread, start a new event pump. 2. If we're
// on any other thread, call wait() on the treelock.
final Container nativeContainer;
synchronized (getTreeLock()) {
nativeContainer = getHeavyweightContainer();
if (nativeContainer.modalComp != null) {
this.modalComp = nativeContainer.modalComp;
nativeContainer.modalComp = this;
return;
}
else {
nativeContainer.modalComp = this;
}
}
Runnable pumpEventsForHierarchy = new Runnable() {
public void run() {
EventDispatchThread dispatchThread =
(EventDispatchThread)Thread.currentThread();
dispatchThread.pumpEventsForHierarchy(
new Conditional() {
public boolean evaluate() {
return ((windowClosingException == null) && (nativeContainer.modalComp != null)) ;
}
}, Container.this);
}
};
if (EventQueue.isDispatchThread()) {
SequencedEvent currentSequencedEvent =
KeyboardFocusManager.getCurrentKeyboardFocusManager().
getCurrentSequencedEvent();
if (currentSequencedEvent != null) {
currentSequencedEvent.dispose();
}
pumpEventsForHierarchy.run();
} else {
synchronized (getTreeLock()) {
Toolkit.getEventQueue().
postEvent(new PeerEvent(this,
pumpEventsForHierarchy,
PeerEvent.PRIORITY_EVENT));
while ((windowClosingException == null) &&
(nativeContainer.modalComp != null))
{
try {
getTreeLock().wait();
} catch (InterruptedException e) {
break;
}
}
}
}
if (windowClosingException != null) {
windowClosingException.fillInStackTrace();
throw windowClosingException;
}
if (predictedFocusOwner != null) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().
dequeueKeyEvents(time, predictedFocusOwner);
}
}
private void stopLWModal() {
synchronized (getTreeLock()) {
if (modalAppContext != null) {
Container nativeContainer = getHeavyweightContainer();
if(nativeContainer != null) {
if (this.modalComp != null) {
nativeContainer.modalComp = this.modalComp;
this.modalComp = null;
return;
}
else {
nativeContainer.modalComp = null;
}
}
// Wake up event dispatch thread on which the dialog was
// initially shown
SunToolkit.postEvent(modalAppContext,
new PeerEvent(this,
new WakingRunnable(),
PeerEvent.PRIORITY_EVENT));
}
EventQueue.invokeLater(new WakingRunnable());
getTreeLock().notifyAll();
}
}
final static class WakingRunnable implements Runnable {
public void run() {
}
}
/* End of JOptionPane support code */
/**
* Returns a string representing the state of this <code>Container.
* This method is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not be
* <code>null.
*
* @return the parameter string of this container
*/
protected String paramString() {
String str = super.paramString();
LayoutManager layoutMgr = this.layoutMgr;
if (layoutMgr != null) {
str += ",layout=" + layoutMgr.getClass().getName();
}
return str;
}
/**
* Prints a listing of this container to the specified output
* stream. The listing starts at the specified indentation.
* <p>
* The immediate children of the container are printed with
* an indentation of <code>indent+1. The children
* of those children are printed at <code>indent+2
* and so on.
*
* @param out a print stream
* @param indent the number of spaces to indent
* @throws NullPointerException if {@code out} is {@code null}
* @see Component#list(java.io.PrintStream, int)
* @since JDK1.0
*/
public void list(PrintStream out, int indent) {
super.list(out, indent);
synchronized(getTreeLock()) {
for (int i = 0; i < component.size(); i++) {
Component comp = component.get(i);
if (comp != null) {
comp.list(out, indent+1);
}
}
}
}
/**
* Prints out a list, starting at the specified indentation,
* to the specified print writer.
* <p>
* The immediate children of the container are printed with
* an indentation of <code>indent+1. The children
* of those children are printed at <code>indent+2
* and so on.
*
* @param out a print writer
* @param indent the number of spaces to indent
* @throws NullPointerException if {@code out} is {@code null}
* @see Component#list(java.io.PrintWriter, int)
* @since JDK1.1
*/
public void list(PrintWriter out, int indent) {
super.list(out, indent);
synchronized(getTreeLock()) {
for (int i = 0; i < component.size(); i++) {
Component comp = component.get(i);
if (comp != null) {
comp.list(out, indent+1);
}
}
}
}
/**
* Sets the focus traversal keys for a given traversal operation for this
* Container.
* <p>
* The default values for a Container's focus traversal keys are
* implementation-dependent. Sun recommends that all implementations for a
* particular native platform use the same default values. The
* recommendations for Windows and Unix are listed below. These
* recommendations are used in the Sun AWT implementations.
*
* <table border=1 summary="Recommended default values for a Container's focus traversal keys">
* <tr>
* <th>Identifier
* <th>Meaning
* <th>Default
* </tr>
* <tr>
* <td>KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS | * <td>Go down one focus traversal cycle |
... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.